Mohammad Moghimi
Mohammad Moghimi

Reputation: 4696

ImageMagick convert resize by the smaller dimension?

The following command resizes the larger dimension to 256:

convert -resize 256x256 in.jpg out.jpg

For example, if in.jpg is 1024x512, it resizes it to 256x128.

Is it possible to resize the smaller dimension to 256 (while keeping the aspect ratio) with ImageMagick convert? (I need 512x256)

If not, is there any other easy command line solution?

Upvotes: 4

Views: 3388

Answers (2)

nwellnhof
nwellnhof

Reputation: 33658

The fill area flag ^ seems to do exactly what you want:

convert -resize 256x256^ in.jpg out.jpg

If you're on Windows:

The Fill Area Flag ('^' flag) is a special character in Window batch scripts and you will need to escape that character by doubling it. For example '^^', or it will not work.

This only works with ImageMagick 6.3.8-3 and above. For older versions, use this trick.

Upvotes: 4

Mark Setchell
Mark Setchell

Reputation: 208052

Maybe the command I suggested in my comment will work, namely

convert in.jpg -resize x256 out.jpg

Or, if you actually want to identify the smaller dimension and resize that explicitly, this should do the trick

#!/bin/bash
image=$1
cmd="x256"
[ $(identify -format "%[fx:w<h?1:0]" "$image") -eq 1 ] && cmd="256x"
convert "$image" -resize $cmd out.jpg

I preset the command to resize by height at line 3. Then I ask ImageMagick to output 1 if the image is taller than wide, and if it is, I change the resize command to resize by width. Then, finally, I do the actual resize. You can re-cast the script various ways to make it shorter, or leave it explicit.

E.g.

if [ $(identify -format "%[fx:w<h?1:0]" in.jpg) -eq 1 ]; then 
   convert in.jpg -resize x256 out.jpg; 
else 
   convert in.jpg -resize 256x out.jpg; 
fi

Upvotes: 3

Related Questions