Resize image to fill or to fit depending on orientation with CarrierWave and RMagick
If you have an slider maybe you want to do a resize_to_fit
when the picture's orientation is landscape and a resize_to_fill
when is portrait. This is what Airbnb do for their pictures slider.
To do that use this in your CarrierWave Uploader (works with RMagick, it could be adapted for MiniMagick)
version :slider do
process :create_slider_version
end
def create_slider_version
img = Magick::Image.read(current_path)
width = img[0].columns
height = img[0].rows
if width > height
# original is landscape
resize_to_fill(738, 492)
else
# original is portrait
resize_to_fit(738, 492)
end
end
The context for the create_slider_version
method is CarrierWave::Uploader::Base (that's where the method current_path
comes from).
Written by Javier Cuevas
Related protips
1 Response
Thanks a lot, it helped me much for a project I'm currently working on. Here's what I came up with, using MiniMagick, in case it can help anyone.
protected
def process_original_version
image = ::MiniMagick::Image::read(File.binread(@file.file))
if image[:width] > image[:height]
resize_to_fill 1600, 1200
else
resize_to_fill 1200, 1600
end
end
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#