1
votes

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"
2
AFAIK, this is not possible with pure IM. One should use ruby helper to read the image and calculate the desired result.Aleksei Matiushkin
This question will probably be best suited to another one of the StackExchange sites; it's more about specific ImageMagick commandsRichard Peck
Just for curiosity, do you really NEED to resize/crop the image? What I mean is that you can use a non square file but square/crop it using the object-fit CSS property. Maybe it's simpler that way and covers your need.arieljuod

2 Answers

1
votes

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.

0
votes

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