Watermarking Images--from the Command Line

Us geeks mostly think of the command line as the best place for text manipulation. It's a natural with cat, grep and shell scripts. But although you can't necessarily view your results from within a typical terminal window, it turns out to be pretty darn easy to analyze and manipulate images from within a shell script.

In my last article, I introduced the splendid open-source ImageMagick suite that offers more features and functionality than you can shake a tree's worth of branches at. Why you would be shaking a tree at a piece of software escapes me, but, hey, I'm just writing this stuff, not thinking about what I'm saying.

Um...wait a sec.

Anyway, ImageMagick includes a variety of programs that let you analyze, manipulate and even convert image files in a remarkable number of different ways.

My last article described setting things up and a few easy ways to confirm that the suite was working correctly on your computer. Now let's start with a simple task that can be useful for web servers: a script that checks image files and flags any that are more than a specific size.

In fact, let's use 8MB because that's the maximum size allowed in Facebook Open Graph, a fact of which many webmasters are already well aware.

Finding Those Big Darn Image Files

Identifying big files can be done with a simple find, but the goal here is to do something more sophisticated, so let's pair it with the ImageMagick command identify.

Here's a loop to identify files bigger than a specified size:

for name in `find *{png,jpg} -size +8M -print`
    echo file $name is bigger than 8MB

That's a good start, but for those image files that match, more detail would be helpful, and I'm not talking ls -l output! Instead, let's replace the rudimentary echo statement with something more advanced:

dimensions=$(identify $name | cut -d\  -f3)
size=$(identify $name | cut -d\  -f7)
echo "File $name ($dimensions) has file size $size"


Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.