Permalink
Browse files

added new crop method to mini_magick processor, works by using "c" at…

… the end of the size string for any thumbnail => "75x75c".

It crops any image without any distortion!!!!
See same examples at http://devo.to/2008/10/19/image-rendering-within-attachment_fu
  • Loading branch information...
1 parent 9d75401 commit ee4ea169b4593b87ebcbd56fbaa91a8bc620300b aka47 committed Oct 19, 2008
Showing with 57 additions and 0 deletions.
  1. +57 −0 lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
@@ -47,6 +47,63 @@ def resize_image(img, size)
else
commands.resize(size.join('x') + '!')
end
+ # extend to thumbnail size
+ elsif size.is_a?(String) and size =~ /e$/
+ size = size.gsub(/e/, '')
+ commands.resize(size.to_s + '>')
+ commands.background('#ffffff')
+ commands.gravity('center')
+ commands.extent(size)
+ # crop thumbnail, the smart way
+ elsif size.is_a?(String) and size =~ /c$/
+ size = size.gsub(/c/, '')
+
+ # calculate sizes and aspect ratio
+ thumb_width, thumb_height = size.split("x")
+ thumb_width = thumb_width.to_f
+ thumb_height = thumb_height.to_f
+
+ thumb_aspect = thumb_width.to_f / thumb_height.to_f
+ image_width, image_height = img[:width].to_f, img[:height].to_f
+ image_aspect = image_width / image_height
+
+ # only crop if image is not smaller in both dimensions
+ unless image_width < thumb_width and image_height < thumb_height
+
+ # special cases, image smaller in one dimension then thumbsize
+ if image_width < thumb_width
+ offset = (image_height / 2) - (thumb_height / 2)
+ command = "#{image_width}x#{thumb_height}+0+#{offset}"
+ elsif image_height < thumb_height
+ offset = (image_width / 2) - (thumb_width / 2)
+ command = "#{thumb_width}x#{image_height}+#{offset}+0"
+
+ # normal thumbnail generation
+ # calculate height and offset y, width is fixed
+ elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height
+ height = image_width / thumb_aspect
+ offset = (image_height / 2) - (height / 2)
+ command = "#{image_width}x#{height}+0+#{offset}"
+ # calculate width and offset x, height is fixed
+ else
+ width = image_height * thumb_aspect
+ offset = (image_width / 2) - (width / 2)
+ command = "#{width}x#{image_height}+#{offset}+0"
+ end
+ # crop image
+ commands.extract(command)
+ end
+
+ # don not resize if image is not as height or width then thumbnail
+ if image_width < thumb_width or image_height < thumb_height
+ commands.background('#ffffff')
+ commands.gravity('center')
+ commands.extent(size)
+ # resize image
+ else
+ commands.resize("#{size.to_s}")
+ end
+ # crop end
else
commands.resize(size.to_s)
end

0 comments on commit ee4ea16

Please sign in to comment.