Given an image, how do I use imagemagick to resize it to a specific aspect ratio? for example, to an aspect ratio of 2:1
Ubuntu – imagemagick crop images to specific aspect ratio
imagemagick
imagemagick
Given an image, how do I use imagemagick to resize it to a specific aspect ratio? for example, to an aspect ratio of 2:1
Best Answer
Two things to consider:
I address each in turn:
1. Simple resizing with or without aspect ratio conversion
imagemagick
by default will maintain the preexisting aspect ratio of an image during conversions. Using this test image:which conveniently has the dimensions of 100x100 an attempt to resize to 300x150 with this syntax will silently fail:
and will produce a 150x150 image:
To force
imagemagick
to actually produce your 2:1 aspect ratio image the following slightly different syntax is required:And this achieves a 2:1 aspect ratio, with distortion of the original image of course:
2. Cropping with aspect ration conversion
If you would prefer to simply and automatically crop an image to a specified aspect ratio the easiest way is to use one of Fred's ImageMagick Scripts: 'Aspectcrop'. Usage on our test image is simply:
and the resulting image has been successfully cropped to a 2:1 ratio:
The other option to be manipulated is
-g gravity
which defines which part of the image is used for cropping. The default is center, all options are:So to give an example of this using north:
The results are:
If you needed to use this script for a batch load of images in a single directory you could use a bash 'for' loop. First place the script correctly and set it to executable:
This makes it a lot easier to use the script. Then run the 'for' loop from within a directory of images:
This loop can be varied according to the type of input and output files, different locations etc. You could also produce a similar syntax that will search recursively for images. Lots of possibilities...
I think that is all pretty cool :)
References: