Making Image Thumbnails with ImageMagick

Creating thumbnail images for your website can be a time consuming task if performed in a capable bitmap editing program. However, it is entirely possible to automate or at least reduce the number of steps needed to perform this process using the command line tool ImageMagick. Personally, I use this tool on Mac, Linux, and Windows.

I moved this website from Drupal 8 to a homegrown implementation using my favorite LAMP stack technologies, and as a result I lost the automatic image thumbnail capabilities provided by that platform. No worries though. With a relatively simple command, creating a thumbnail image is a snap!

Current Thumbnail Requirements

It is a good idea to formalize the type of thumbnail images your website requires. For jtpresta.com, I need only one variant currently, and which is used for the galleries and is responsive-design friendly. You might find it helpful to actually write down your specification and keep it somewhere close to your website installation source code.

The Thumbnail Spec

    Width:   400 pixels
    Height:  400 pixels
    Quality: JPEG, 50%

    * All thumbnails must be the same final size!
  

Well that seems simple enough, right?

Wait. There is a problem here. What if the original images are not the same relative dimensions? Ideally, we would want to scale the original images to a percentage based on the original dimensions. Unfortunately, most of the images used so far on this website are in portrait and landscape formats. If these are scaled down with a fixed percentage, it will not be possible to achieve the 400x400 target without merging the scaled image onto a fixed dimension bitmap. In other words...more work when we want quick and painless.

There's a Tradeoff

The simple solution is to allow cropping of the original image, so only a portion of it will be revealed in the thumbnail image. This is of course a non-issue since the thumbnail itself will be a "teaser" anyway and should entice the viewer to check out the full thing.

The ImageMagick Command Itself

Whew! That was a lot of text just to get down to a single line command, eh? Away we go!

   convert original-image.jpg -resize 400x400^ -quality 50% -gravity center -crop 400x400+0+0 +repage thumbnail-image.jpg
  
The final result is below and is based on a 1600x1200 PNG file converted to JPEG.

Before and after

Cheers!