ImageMagick: Batch Crop and Rename Files

There are many better ways to do this, but here is one method if you need to do a quick and dirty jobs of cropping and renaming a bunch of files in a batch with ImageMagick.

Quick little background. Even though I’ve got a Macbook, if I have to look at code, I’m usually on a desktop thats running Ubuntu 10.04. We host client sites on servers running Ubuntu 10.04, so its best to write code in that environment. So today, after finishing up code for a Magento site, I needed to upload a set of fabric swatches that would be used with configurable products. The client provided images for the fabric swatches, but they were all different sizes. All I needed was a 60x60px selection of each image and the filenames to be something descriptive with the image size.

Of course, this can be done pretty easily in Photoshop. I’m sure there is some plugin for it, but you can record an action, and run it against a batch of files. The problem was that I didn’t want to hop on my Macbook just to crop and rename files.

Since I was on an Ubuntu machine, my first gut reaction was to fire up Gimp and see if I could do it. Turns out there is a plugin called David’s Batch Processor that pretty much does that. Ubuntu has the plugin in the repository, just search for ‘gimp-plugin-registry’ in Synaptic. Gimp also supports scripting, but the scripting language is Scheme-like, and I didn’t want to recall knowledge from freshman year in college to do this.

Then I remembered ImageMagick. While ImageMagick has a GUI for image manipulation, its got a powerful CLI that lets you do pretty much anything you want to do. So no need to open up a big honkin’ application just to do some basic cropping and renaming.

So save the following code in the directory of the files you want cropped and renamed and run it:

#!/bin/bash
width=60;
height=60;
x_offset=10;
y_offset=5;
filelist=`ls | grep '.jpg'`
for image_file in $filelist
do
  preextensionfilename=`convert $image_file -format "%t" info:`
  convert $image_file -crop ${width}x${height}+${x_offset}+${y_offset} \
    ${preextensionfilename}_${width}x${height}.jpg
done

Most of this should be pretty self-explanatory. Up top we define what sizes we want the images to be cropped to and from where in the image we want to crop. Then we grab a list of all the files we want to crop, and grab the filename before the extension (to be used for saving the new files). The convert command is what actually does the cropping and saving the files with the new names, in this case, something like oldgold_60x60.jpg.

The script is most definitely not robust, but hopefully it will be a good starting off point for some.