Monday, April 05, 2010

Crop White-space From Images

One of the most frequent batch tasks I have to perform is to crop the white-space on multiple images. I find that a quick and easy bash script that uses ImageMagick's convert function is the simplest option. This is what bash is great for for the casual user.

ImageMagick is a suite of command line tools for manipulating images. You should be able to install it on most linux type distributions via their respective package manager, as well as on Windows via cygwin and MAC OSX.

The script is unbelievably simple. This version does destroy the original image, which is replaced with the cropped one

The script:

#!/bin/bash
# bash script for cropping
# a directory of a .pngs 2010-04-02

for X in *.png
do
echo $X
convert -trim $X $X
done

exit

# eof


I save the file as convert.sh, copy it to the directory full of images that I'm working with and run it from the command line:

$ bash convert.sh

Alternately you can make the file executable, and keep it somewhere in your $PATH but I tend not to bother with these kind of utility scripts.

If you want to preserve the original file you could make a backup by adding this line after the echo statement:

$ cp $X "$X.bak"

Or change the convert statement to uniquely identity the cropped image:

convert -trim $X "cropped_$X"

or some such thing. I'm sure there are more ways to do this little task, but with these down and dirty scripts one wants to be able to simply write something quickly that works.

No comments: