How to use the ImageMagick 'convert' command to add a border to many images

I just used this ImageMagick code in a Unix shell script to add a 20% black border to every image in the current directory:

for i in `ls`
do
    name="mod_$i"
    echo "working on $name ..."
    convert $i -bordercolor black -border 20%x20% $name
done

The script uses the ImageMagick convert command inside a Unix for loop to convert every file. I guess I should note that it doesn’t actually convert each file; it makes a copy of the file with the prefix “mod_” prepended to the name, so an image named foo.jpg is used as input and copied to a new image named mod_foo.jpg, and this new image has the 20% black border.

All of my images are different sizes, so I used a “percentage” value for the border size. You can also specify pixel sizes. See this link for more information.

Note: When you specify the border color, the -bordercolor option needs to come before the -border option. It took me ten minutes to figure that out.

Running the script

I put the code shown in a file named convertall.sh, then ran that script like this:

$ sh convertall.sh

The convert command comes from ImageMagick, so you need to have it installed. On a Mac OS X system you can use Brew or MacPorts to install it. On Linux systems use whatever package manager you normally use, i.e., apt-get, yum, or whatever.

Example

Over the last few days I’ve downloaded a lot of yoga images that I now use as screensaver images, so as one example, I start with an image like this:

and then add a black border to make the resulting image look like this:

Adding a large border to the image makes it work better with the Mac OS X “Ken Burns” screensaver.

I have these yoga screensaver images running on an old 27” iMac in what is currently a very large kitchen, and I find that constantly seeing the images is an inspiration for my practice. It’s hard to walk by the images without striking a pose myself. :)