user3001153
user3001153

Reputation: 23

Resizing image with ImageMagick and Ruby on Rails

I have been trying to use Imagemagick to resize images uploaded by a user as a square.

Currently, I am using the ! like so - 640x640!

This works fine if the image i feed it is a resolution of 640x640 or bigger - it resizes and makes it into a square as expected.

The problem is that if either the height or width of the image is smaller than 640, then it wont square it out. For instance if the image is 480x600, it wont do anything to the image. Similarly if the image is 680x456 then it will resize it to 640x456

How can i make it so that it will always square the image to a maximum size of 640x640? If the image is greater than 640x640, then i want it to resize to 640x640. If the image is smaller than 640x640, i.e. 480x600, i want it to resize to 480x480

I'm doing it in rails, within the paperclip attachment definition, like this:

has_attached_file :avatar, :styles => { :medium => "640x640!", :thumb => "150x150!" }, :default_url => "/images/:style/missing.png"

Upvotes: 2

Views: 3846

Answers (2)

Arvind singh
Arvind singh

Reputation: 1392

Making it always square may loose images's aspect ratio. Here are couple of ways to resize the image.

resize_to_limit

Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Will only resize the image if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.

resize_to_fit

Resize the image to fit within the specified dimensions while retaining the original aspect ratio. The image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.

resize_to_fill

Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension.

This one is Image Magick Way

http://www.imagemagick.org/discourse-server/viewtopic.php?t=26196#p115047

Upvotes: 0

noe
noe

Reputation: 224

First, Require the library

  require 'rubygems'
  require 'mini_magick'

Second, You have to get the image first

image = MiniMagick::Image.open("PathOfTheImage")

Next, resize it

image.resize "640x640!"

finally, save the image

image.write "output.png"

and use the output image afterwards.

Upvotes: 1

Related Questions