Rails + Carrierwave + RMagick: crop only if the image is large

I use a carrier wave to upload images. When loading, I create thumbnails for the image, which is performed using the Rmagick method, resize_to_fill, as shown below.

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

It displays all the methods RMagick carrierwave supports (none of which I want):

  • :resize_to_fill => [150,150]

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

  1. :resize_to_fit => [150,150]

It has changed again, I want him to be alone!

: resize_to_fit => [150,150]

  1. :resize_to_limit => [150,150]

This leaves it as it is, but large images are not cropped. They are modified to maintain aspect ratio.

enter image description here

enter image description here

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

enter image description hereenter image description here

How to do it? I want smaller images to stay alone and crop only large images to 150 x 150. Is there any other way or parameters that I can pass to resize_to_fill?

+4
source share
1 answer

I solved it by changing the method :resize_to_fill carrierwave, as described in their code here .

I just made a new method with the same validation code to reduce the loaded image. Here is a 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? img end end 

Exactly what I want now.

+6
source

Source: https://habr.com/ru/post/1501220/


All Articles