Friday, February 10, 2012

specular reflection with mini_magick (2)

(continued from phosphorescence: specular reflection with mini_magick (1))

"Specular Reflection" consists of 4 operations.
  1. clone from original image and rotate it
  2. add transparency to cloned image
  3. combine original image and cloned one
  4. resize combined image
In this article, I introduce the operation of both (3) and (4) with referring ImageMagick's sample page and using mini_magick. Roughly instructions are below:

  1. Create canvas with extending the vertical length
  2. Put the rotated image onto the bottom of this canvas
  3. Put the original image onto the top of this canvas

Sample of concrete implementation is below:
require 'mini_magick'

original_file = "original.jpg"

image_cloned = MiniMagick::Image.open(original_file)

background_color = 'black' # set background color
COMPOSITE_GRAVITY = 'north'
TRANSPARENCY = '65%'
REFLECTION_FACTOR = Math.sqrt(2)

image_cloned.combine_options do |mogrify|
  mogrify.flip
  mogrify.fill background_color
  mogrify.colorize TRANSPARENCY
end

image_original = MiniMagick::Image.open(original_file)

image_cloned.combine_options(:convert) do |convert|
  new_width = image_original[:width]
  new_height = (image_original[:height]*REFLECTION_FACTOR).to_i
  convert.size "#{new_width}x#{new_height}"
  convert.xc background_color
  convert.swap '0,1'
  convert.gravity COMPOSITE_GRAVITY
  convert.geometry "+0+#{image_original[:height]}"
  convert.composite
end

image_combined = image_cloned.composite(image_original) do |c|
  c.gravity COMPOSITE_GRAVITY
end

output_file = "reflected_#{background_color}.jpg"
image_combined.write output_file
puts "#{output_file} is generated."

These are the output samples.

for white background:

for black background:

No comments:

Post a Comment