Shaunak Shaunak - 2 years ago 115
Ruby Question

Rails + Carrierwave + RMagick : Crop only if image is large

I am using carrier-wave to upload images. On upload I am creating thumbnails for the image which is done using Rmagick method, resize_to_fill like below.

version :thumb do
process :resize_to_fill=> [150, 150]

Here is output of all the RMagick methods carrierwave supports (none of which I want):

  1. :resize_to_fill => [150,150]

This works fine on larger images but my smaller images are enlarged to 150 x 150.
:resize_to_fill => [150,150]

  1. :resize_to_fit => [150,150]

Again it was resized, I want it left alone!

:resize_to_fit => [150,150]

  1. :resize_to_limit => [150,150]

This one leaves it as is, but larger images are not cropped. They are resized to keep the aspect ratio.

enter image description here

enter image description here

Here is the result I want and how my small and larger images should look.

enter image description here
enter image description here

How do this? I want smaller images to be left alone and crop only larger images to 150 x 150. Is there another method or options I can pass to resize_to_fill?

Answer Source

I solved it by modifying :resize_to_fill carrierwave method as described in their code here.

I just made a new method with the same code with a check to see if the uploaded image is smaller. Here is the new method:

def resize_to_fill_modfied(width, height, gravity=::Magick::CenterGravity)
      manipulate! do |img|
        img.crop_resized!(width, height, gravity) unless (img.columns <= width && img.rows <= height)
        img = yield(img) if block_given?

Does exactly what I want now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download