Search code examples
resizeimagemagickaspect-ratio

ImageMagick losing aspect ratio


Very simply I have a script that calls imagemagick on my photos.

The original image is 320 x 444, and I want to create a few scaled down versions but keeping the same aspect ratio

I call imagemagick using

convert oldfile.png -resize 290x newfile.png

I want to scale it to my set widths but the heights scale accordingly.

I do 80x, 160x and 290x in 3 separate commands.

The smallest 2 produce images with the same original aspect ratio, the 290x does not.

The size of the image it produces is 290 x 402

I have no idea why that one fails to keep the aspect ratio but the other 2 sizes maintaine it.

Any ideas?


Solution

  • I think that the problem in the third command is the requested size itself:

    1. in the first command both dimensions are divided by 4: 320/4=80 and 444/4=111
    2. in the second command both dimensions are divided by 2: 320/2=160 and 444/2=222

    444 and 320 have only two common divisors: 2 and 4. You already used these divisors in your first two commands, so any other (width, height) couple will give you a slightly different aspect ratio: it is impossible to obtain the same exact aspect ratio fixing 290.

    In fact while your original image has an aspect ratio of 1.3875, with a 290x403 image you would obtain an aspect ratio of 1,389655172 and with a 290x402 image you would get a 1,386206897 ratio: fixing 290 there is no other dimension's value that can give you the desired aspect ratio.

    In general however Imagemagick always tries to preserve the aspect ratio of the image, as you can read in Imagemagick documentation:

    The argument to the resize operator is the area into which the image should be fitted. This area is not the final size of the image but the maximum sizes for the image. that is because IM tries to preserve the aspect ratio of the image more than the final (unless a '!' flag is given), but at least one (if not both) of the final dimensions should match the argument given image. So let me be clear... Resize will fit the image into the requested size. It does NOT fill, the requested box size.

    For further reference see here