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:
- 1Linux Top 3: Alpine Linux 3.4, deepin 15.2 and Linux Lite 3.0
- 2Linux 4.7 Set to Boost Live Patching, Security and Power Management
- 3Linux 4.6 Charred Weasel adds USB 3.1 Support
- 4Linux Top 3: OpenIndiana 2016.04, Ubuntu 16.04 and Debian's New Leader
- 5Linux Top 3: KaOS 2016.04, TurnKey 14.1 and pfSense 2.3