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:
Solid state disks (SSDs) made a splash in consumer technology, and now the technology has its eyes on the enterprise storage market. Download this eBook to see what SSDs can do for your infrastructure and review the pros and cons of this potentially game-changing storage technology.
- 1Linux Top 3: GNOME 3.12 and New Betas for Ubuntu 14.04 and OpenMandriva Lx 2014.0
- 2Linux Top 3: Linus Lashes out, Linux 3.14 Gets PIE and Ubuntu One is Done.
- 3Linux Top 3: Ubuntu 14.04, Debian Gives Squeeze More Life and Red Hat Goes Atomic
- 4Linux Top 3: Linux 3.11, Kubuntu Goes Commercial
- 5Linux Top 3: RHEL 6.5, Debian 7.2 and EOL for Linux 3.0.x