Jens Nöckel's Homepage

Computer notes home

ImageMagick and auto-cropping

Imagemagick is an open-source collection of graphics utilities which includes the convert command. This command makes it possible to scale, compress and otherwise manipulate images of many different types, including both bitmap (jpeg, gif etc.) and vector formats (pdf etc.). It used to be possible to crop images automatically by including the command-line option convert -crop 0x0. In some versions of this software on Mac OS X, this option doesn't work. In my current version of the software, images can be cropped by typing convert -trim instead. If this does not work for you (there was a period when this did not work on my system), you may want to read on.

As a workaround, one can use the following combination (which you can store as an executable shell script, perhaps call it cropImage):

#!/bin/tcsh
/sw/bin/convert $1 /tmp/`echo $1 | cut -f1 -d'.'`-pnmcrop.ppm
/sw/bin/pnmcrop /tmp/`echo $1 | cut -f1 -d'.'`-pnmcrop.ppm | convert -quality 100 - cropped-$1
rm /tmp/`echo $1 | cut -f1 -d'.'`-pnmcrop.ppm
The script takes one argument: the image file name (which can be any image format recognized by convert. The cropped image is stored as a file with the prefix "cropped-". It may be possible to shorten this script by replacing `echo $1 | cut -f1 -d'.'` with $1; the purpose of the longer expression is to cut off the original suffix (e.g., .jpg so that the resulting file names don't look like foo.jpg.ppm which might potentially confuse the convert program.

As prerequisites you need to install the packages imagemagick and netpbm from fink. See also my general installation instructions.


Jens Nöckel
Last modified: Wed Apr 20 23:10:13 PDT 2005