Manipulate Images with ImageMagick

Armed with that knowledge, conversion between image file formats is really ridiculously simple. Let's say you want to convert an image from JPEG to PNG. It's as simple as:


convert image.jpeg image.png

Since the ImageMagick utilities are glob-aware (that is, you can use wild cards and specify multiple filenames), you also can convert a group of GIF images to JPG with the convert command or, more easily, with its cousin mogrify:


mogrify -format jpg *.gif

Let's give it a whirl with a folder that contains a half-dozen GIF images, using ls to show the folder contents before and after the mogrification (is that a word?):


$ ls -s
total 272
  8 add-to-google-reader.gif     24 blogger-1.gif
  8 dave.gif                    8 add-to-newsgator.gif
 24 blogger-2.gif                    176 manga.gif
 16 aw-logo.gif                   8 blogger-3.gif
$ mogrify -format jpg *gif
$ ls -s
total 752
  8 add-to-google-reader.gif     24 blogger-1.gif
  8 dave.gif                    8 add-to-google-reader.jpg
112 blogger-1.jpg                      8 dave.jpg
  8 add-to-newsgator.gif              24 blogger-2.gif
176 manga.gif                   8 add-to-newsgator.jpg
128 blogger-2.jpg                    168 manga.jpg
 16 aw-logo.gif                   8 blogger-3.gif
 24 aw-logo.jpg                  24 blogger-3.jpg

Simple enough. Use convert for individual images and mogrify for bulk conversions. It'd be an easy script to differentiate between these two cases and invoke the correct command with the correct arguments too. I'll leave that up to you!

Checking Image Sizes

Another useful feature of the ImageMagick suite is to be able to identify the dimensions of a graphic image. The latest version of the file command can offer this information on some systems:


$ file manga*
manga.gif: GIF image data, version 89a, 358 x 313
manga.jpg: JPEG image data, JFIF standard 1.01,
 ↪aspect ratio, density 1x1, segment length 16,
 ↪baseline, precision 8, 358x313, frames 3
manga.png: PNG image data, 358 x 313, 8-bit/color RGB,
 ↪non-interlaced

But on most Linux systems, one or more of these would exclude the actual dimensions. Further, look closely at the above output, and you'll see it's quite inconsistent, making it difficult to parse out the dimensions if you don't encode specific rules for each format—which is, uh, lame.

______________________

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.