Created
May 8, 2021 00:30
-
-
Save mbijon/3a5f42ed884f6dfe740f1c50fc8063f6 to your computer and use it in GitHub Desktop.
Example of complex blur using Image Magick + mini_magick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright Ognjen Regoje, 2021 | |
# https://ognjen.io/generating-more-interesting-image-previews-using-imagemagick/ | |
# | |
#### | |
require 'mini_magick' | |
INPUT_FILE = "input-1-lg.jpg" | |
image = MiniMagick::Image.open(INPUT_FILE) | |
size = image.dimensions.map{|x| x} | |
height = size[0] | |
width = size[1] | |
density = 10 | |
sh = height / density | |
sw = width / density | |
fragments = [] | |
hh = height / 2 | |
hw = width / 2 | |
density.times do |w| | |
density.times do |h| | |
c = rand | |
prob = 1 - ((((hw.to_f - (w*sw).to_f).abs / hw.to_f) + (hh.to_f - (h*sh).to_f).abs / hh.to_f) / 2) | |
if c < prob | |
fragments.push({w: w*sw, h: h*sh}) | |
convert = MiniMagick::Tool::Convert.new | |
convert << INPUT_FILE | |
convert.crop("#{sh}x#{sw}+#{h*sh}+#{w*sw}") | |
convert.blur("0x200") | |
convert.fill("black") | |
convert.draw("polygon #{sh/2},#{sw} #{sh},#{sw} #{sh},0") # Use sh/2 instead of just sh so that the "triangle" starts in the middle rather then in the corner to cover more of the image | |
convert.fuzz("15%") | |
convert.define('png:color-type=6') | |
convert.transparent("black") | |
convert << "output-crop-with-triangle-#{w*sw}-#{h*sh}.png" | |
convert.call | |
end | |
end | |
end | |
image = MiniMagick::Image.open(INPUT_FILE) | |
fragments.each do |x| | |
cropped = MiniMagick::Image.new("output-crop-with-triangle-#{x[:w]}-#{x[:h]}.png") | |
result = image.composite(cropped) do |c| | |
c.compose "Over" | |
c.geometry "+#{x[:h]}+#{x[:w]}" | |
end | |
result.write "image-previews-output-with-probability-transparent-triangles.jpg" | |
File.delete("output-crop-with-triangle-#{x[:w]}-#{x[:h]}.png") | |
if fragments.last != x | |
image = MiniMagick::Image.open("image-previews-output-with-probability-transparent-triangles.jpg") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment