Skip to content

Instantly share code, notes, and snippets.

@jbn
Created November 22, 2010 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbn/709408 to your computer and use it in GitHub Desktop.
Save jbn/709408 to your computer and use it in GitHub Desktop.
module MiniMagick
class Image
# Size is in 'WidthxHeight' string format.
def resize_and_crop(target_size)
target_width, target_height = *target_size.split('x').collect{|x| x.to_f}
width, height = self[:width].to_f, self[:height].to_f
# If the width or height are already less than the targets
# just take the extent -- no resizing nessessary.
if width >= target_width && height >= target_height
width_ratio, height_ratio = target_width/width, target_height/height
# There are only two possible transformations:
# * dimensions scaled by the width_ratio
# * scaled by the height_ratio.
#
# Reject the transformation if either dimension is
# smaller than the respective target dimension.
#
# Sort the transformations by pixels.
#
# Select the first remaining, sorted transformation.
transformation = [
[target_width, (height * width_ratio).ceil],
[(width * height_ratio).ceil, target_height]
].reject{|t| t[0] < target_width || t[1] < target_height}.
sort{|a,b| (a[0]*a[1]) <=> (b[0]*b[1])}.
first.collect{|dim| dim.to_i}
# Resize it
self.resize("#{transformation[0]}x#{transformation[1]})")
end
self.combine_options do |c|
c.gravity 'North'
c.background 'White'
c.extent(target_size)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment