imagemagick crop images to specific aspect ratio?

Two things to consider:

  1. Simple resizing with or without aspect ratio conversion
  2. Cropping with aspect ration conversion

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:

enter image description here

which conveniently has the dimensions of 100x100 an attempt to resize to 300x150 with this syntax will silently fail:

convert test.png -resize 300x150 300_test.png

and will produce a 150x150 image:

enter image description here

To force imagemagickto actually produce your 2:1 aspect ratio image the following slightly different syntax is required:

convert test.png -resize 300x150\! distort.png

And this achieves a 2:1 aspect ratio, with distortion of the original image of course:

enter image description here

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:

./aspectcrop -a 2:1 test.png Fred_wins.png

and the resulting image has been successfully cropped to a 2:1 ratio:

enter image description here

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:

  1. center (c)
  2. north (n)
  3. south (s)
  4. east (e)
  5. west (w)
  6. northwest (nw)
  7. northeast (ne)
  8. southwest, (sw)
  9. southeast (se)

So to give an example of this using north:

./aspectcrop -a 2:1 -g n test.png north.png

The results are:

enter image description here

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:

sudo mv aspectcrop /usr/local/bin
sudo chmod +x /usr/local/bin/aspectcrop

This makes it a lot easier to use the script. Then run the 'for' loop from within a directory of images:

for i in *.png
do 
aspectcrop -a 2:1 -g n "$i" "${i%.png}_cropped.png"
done

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:

  • Imagemagick: Resize or Scaling (General Techniques)
  • Fred's ImageMagick Scripts: 'Aspectcrop'

Tags:

Imagemagick