Rahul
Rahul

Reputation: 47096

Gem to crop image to multiple sizes in rails

When the user updates an image, I would like to crop it to different sizes to suit different specifications in the application like a bigger size image for profile page, a smaller image for comments etc. Is there any gem available for this in rails?

Upvotes: 2

Views: 1363

Answers (3)

HectorMalot
HectorMalot

Reputation: 1120

I would advise you to use the Paperclip gem for this. With it, you can define several sizes for your image. You do need to have ImageMagick installed for this to work. Your ruby model would have a line like this:

has_attached_file :image, :styles => { :small => "150x150>", :medium => "400x400#", :large => "640x640" }

The default behavior is to resize to the smallest dimension and keep the aspect ratio. You can use some options to change this:

  1. trailing #, thumbnail will be centrally cropped, ensuring the requested dimensions.
  2. trailing >, thumbnail will only be modified if it is currently larger requested dimensions.

In your code you can then request the image using image_tag @model.image.url(:small) in your view.

Ryan bates has an excellent railscast on this if you want more information. Paperclip also has an extensive wiki on GitHub.

Upvotes: 3

Erik Hinton
Erik Hinton

Reputation: 1946

The most lightweight image manipulation library/gem that I know of is Devil. ImageMagick/Cairo can be a pain to install. I've never had any problems with DeviL. Cheers.

Upvotes: 0

fl00r
fl00r

Reputation: 83680

Try paperclip gem or carrierwave to work with attaches

Also you can checkout ImageMagick, RMagick or ImageScience projects

Upvotes: 1

Related Questions