With imagemagick, I'd like to crop an image, in a minimal fashion, so that it fits a given aspect ratio.
Example: given an image of, say, 3038 x 2014 px, I want to crop it to have a 3:2 aspect ratio. The resulting image would then be 3021 x 2014 px, cropped from the, say, center of the original image.
So looking for a command looking something like convert in.jpg -gravity center -crop_to_aspect_ratio 3:2 out.jpg
.
1. Specific target resolution
If your goal at the end is to have a certain resolution (for example 1920x1080) then it's easy, using
-geometry
, the circumflex/hat/roof/house symbol (^
) and-crop
:To loop over multiple jpg files:
2. Aspect ratio crop only
If you want to avoid scaling you have to calculate the new length of the cropped side outside of Imagemagick. This is more involved:
I'm using 16:9 in the examples, expecting it to be more useful than 3:2 to most readers. Change both occurences of
1920x1080
in solution 1 or theaw
/ah
variables in solution 2 to get your desired aspect ratio.You need to work out the reqired dimensions and then do a crop. Here's a function that, given the image's
width
andheight
plus the required aspect ratio asaspect_x
andaspect_y
, will output a crop string that can be used with Imagemagick.I'm using something similar to this in an application that uses the Dragonfly Gem.
With the advent of ImageMagick 7 you can use FX expressions to accomplish a crop to the largest image size possible given an aspect ratio in a single command.
The only trick is you're going to need to enter the desired aspect in four different places on the same command so I find it easiest to make a variable for that bit. The aspect can be a decimal number or a fraction as a string that the fx expression can resolve.
Once the aspect is right, you can follow up the two
-extent
operations with a-resize
to bring the finished image to your output size. The example above keeps it as large as it can be given the input image.Recent versions of Imagemagick (since 6.9.9-34) have an aspect crop. So you can do:
Input:
The output is 400x267+0+0. But note that the +repage is needed to remove the virtual canvas of 400x299+0+16, because PNG output supports virtual canvas. JPG output would not need the +repage, since it does not support a virtual canvas.
I needed to split very long images vertically with A4 (1x1.414) paper aspect ratio. So I came up with below solution. Assume image filename is ch1.jpg: