David
David

Reputation: 607

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.

Upvotes: 28

Views: 25155

Answers (3)

Rafael Vidaurre
Rafael Vidaurre

Reputation: 474

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

Upvotes: 13

iwasrobbed
iwasrobbed

Reputation: 46703

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.

Upvotes: 46

JNN
JNN

Reputation: 947

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

Upvotes: 15

Related Questions