Watermarking Images--from the Command Line

Let's assume the watermark graphic is specified with the variable $copy. With that in mind, a nice blend of the two images can be achieved with a 100% dissolve:


composite -dissolve 100 $copy $source $output

That will put the graphic on the top left corner of the resultant image, "above" the underlying photograph or graphic.

You can move it to the lower right by using -gravity—literally. Imagine a compass overlaid on your image: "north" is up, "east" is the right side, "west" is the left side and so on. With the convert -label command shown earlier, the default position was the bottom of the resultant image, so gravity of "east" moved the label to the lower right.

With composite, however, there's a lot more flexibility, so positioning the copyright bug in the lower right involves using a gravity of "southeast"—like this:


composite -dissolve 100 -gravity southeast $copy $source $output

Wrap that in a for loop, and you've got a handy script that can add text watermarks along the bottom or overlay a graphic watermark or copyright instead.

In both cases, notice that the ImageMagick commands always create a new output file. If you want to replace an image with a version that includes a watermark, you'd need to do a bit of file shuffling:


composite -dissolve 100 $copy $source $output
mv $output $source

Ideally though, you'd check to ensure that the composite command worked properly (rather than potentially deleting files or producing a cryptic error). Two ways come to mind: check the error status of the composite command (the sequence $?) or just test for the existence of $output. Here's the latter, since then you aren't reliant on composite having accurate return codes:


composite -dissolve 100 $copy $source $output
if [ -x $output ] ; then
  mv $output $source
else
  echo "Couldn't replace $source, $output wasn't created?"
fi

Is that good? Maybe not. The -x test checks for the existence of the file, but what would be better would be to ensure that the file exists and is non-zero size. That's the -s flag. It's a simple switch, and you've got the basis for a good script.

Magic with Images

The ImageMagick suite contains a number of commands that have dozens to hundreds of parameters. They can be very quirky, as the gravity setting shows—be glad I didn't delve into the geometry parameters—but fortunately, there are lots of online tutorials and help pages.

Remember, it all starts at http://www.imagemagick.org.

______________________

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.