Monday, February 22, 2010

Resize to max width and crop to height using ImageMagick

ImageMagik is a great open source tool that allows many conversions and manipulations of images. It supports huge amount of image types and comes as a command line tool, which makes it very easy to be executed from your favorite programming language.

Resizing an image to a maximum width is an easy task using ImageMagik. It is done with a command line tool named “convert”. For example, if we would like to proportionally resize an image named “image.jpg” to the maximum width of 160 we can do:

convert "c:\image.jpg" -resize 160 "c:\image_out.jpg"

Suppose we would like to do something a bit more complex than proportionally resizing and image to a maximum width: we would like to resize an image to a maximum width, but also crop the image to maximum height. We might want to do this kind of resize, since we want to show group of thumbnails at exactly the same size no matter what is the original image proportions are. Achieving this goal with ImageMagik is an easy task, but adds quite a few complexities to the above command.

For example, if we would like to proportionally resize an image maximum size of 100 pixels and crop the image to height of 80 pixels we have to use the “convert” command this way:

convert "c:\image.jpg" -resize 160x -resize "x160<" -resize 50% -gravity center -crop 100x100+0+0 +repage "c:\image_out.jpg"

If you really want to understand what this set of command exactly do, you can the ImageMagik documentation, which is pretty good. Note that the number 160 is exactly twice than 80. So if we would like to crop an image to height of 100 we would use the number 200.

No comments:

Post a Comment