Skip to content

Instantly share code, notes, and snippets.

@yortz
Forked from soutaro/resize_and_crop.rb
Created August 13, 2011 22:14
Show Gist options
  • Save yortz/1144303 to your computer and use it in GitHub Desktop.
Save yortz/1144303 to your computer and use it in GitHub Desktop.
resize and crop using using MiniMagick
def resize_and_crop(blob, w0, h0, w1, h1)
image = MiniMagick::Image.read(blob)
rw = w1.to_f / w0
rh = h1.to_f / h0
unless rw > 1 or rh > 1
w,h = w1, h1
sx, sy = 0, 0
if rw > rh
h = (h0 * rw).to_i
sy = (h - h1) / 2
else
w = (w0 * rh).to_i
sx = (w - w1) / 2
end
image.thumbnail("#{w}x#{h}")
image.crop("#{w1}x#{h1}+#{sx}+#{sy}")
end
image.to_blob
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment