Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carrierwave - Resizing images to fixed width

I'm using RMagick and want my images to be resized to a fixed width of 100px, and scale the height proportionally. For example, if a user were to upload a 300x900px, I would like it to be scaled to 100x300px.

like image 432
David Avatar asked Dec 20 '11 02:12

David


3 Answers

Just put this in your uploader file:

class ImageUploader < CarrierWave::Uploader::Base

  version :resized do
    # returns an image with a maximum width of 100px 
    # while maintaining the aspect ratio
    # 10000 is used to tell CW that the height is free 
    # and so that it will hit the 100 px width first
    process :resize_to_fit => [100, 10000]
  end

end

Documentation and example here: http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit

Keep in mind, resize_to_fit will scale up images if they are smaller than 100px. If you don't want it to do that, then replace that with resize_to_limit.

like image 99
iwasrobbed Avatar answered Oct 18 '22 19:10

iwasrobbed


I use

process :resize_to_fit => [100, 10000]

Use 10000 or any very big number to let Carrierwave know the height is free, just resize to the width.

@iWasRobbed: I don't think that's the correct solution. According to the link you pasted about resize_to_fit: The maximum height of the resized image. If omitted it defaults to the value of new_width. So in your case process :resize_to_fit => [100, nil] is equivalent to process :resize_to_fit => [100, 100] which doesn't guarantee that you will always get the fixed width of 100px

like image 34
John Nguyen Avatar answered Oct 18 '22 19:10

John Nguyen


Wouldn't a better solution actually be:

process :resize_to_fit => [100, -1]

This way you don't have to limit height at all

EDIT: Just realized this only works with MiniMagick, For RMagick you seem to have no option but to add a large number to the height

like image 13
Rafael Vidaurre Avatar answered Oct 18 '22 19:10

Rafael Vidaurre