Intro to Shell Programming: Writing a Simple Web Gallery - page 2
A Simple Script
Two useful ImageMagick commands are convert and mogrify. The only difference is that convert makes a new file, while mogrify modifies an existing file. (Editor's note: This deserves a bit of emphasis-- mogrify changes your original file, so if you want to keep your original you'll need to make a copy of it first. convert makes a new file, so it does not change your original.)
If you have a big image straight off your digital camera and you want to make it smaller, say 640 pixels, so they won't take forever to download from the web, this command would do it:
mogrify -scale 640 img001.jpg
But for a web image gallery, you'll want to do more than just resize the images; you'll also want thumbnails. That means you'll want a second copy of the file:
convert is better than
mogrify for that. To make a 120-pixel thumbnail, you could say:
convert -scale 120 img001.jpg thumb-img001.jpg
Of course, you don't want to do that for just one file: you want to run convert and mogrify on every image file in the directory. For that, you need a loop.
A loop is just way for a program to do the same thing repeatedly. In this case, it'll do the same thing with each file in the directory. A shell script with a loop might look like this:
#! /bin/sh for img in *.jpg ; do echo $img convert -scale 120 $img thumb-$img mogrify -scale 640 $img done
for starts a loop.
img is the "loop variable": it will represent each image file in turn. If you want to refer to whichever file
img represents inside the loop, add a dollar sign to it:
in *.jpg tells the shell what values will be assigned, one at a time, to
; do means you're done with the list of values to loop over and ready to start the loop.
I've added an "echo" command so you can watch the script at work. Echo in the shell just prints out whatever comes after it, so
echo $img will print the name of the file it's about to convert and mogrify.
Your gallery resizing script is now ready to run! From the shell, when you're already in the image directory, run it like this:
Sponsored by BlackBerry
BlackBerry® Enterprise Server Express enables businesses of any size to quickly and easily get started with the BlackBerry solution. It provides advanced BlackBerry smartphone features with no additional software or user license fees, and works with any Internet-enabled BlackBerry data plan or a BlackBerry enterprise data plan. Download now!