Using ImageMagick to create thumbnails for the web

You can use ImageMagick’s convert tool to resize images on the command line in a Linux, BSD or Windows environment.

The syntax is thus:

  1. convert "/path/to/original.jpeg" -scale 150x150\> -quality 50% -unsharp 1x3+1+.1 -sampling-factor 1x1 -strip "/path/to/new.jpeg"

This breaks down as follows:

  • -scale Resize the image to 150×150 pixels if the image is already larger than that size (as signified by the >). This will not distort the image – rather scale it such that at least one side is 150px.
  • -quality Decrease the JPEG quality by 50% of the original to reduce the file size
  • -unsharp Sharpen the image after resize
  • -strip Strip the profile information. This is important if you don’t require this info in the resized image as I have seen it reduce a 500KB image to 8KB.

Here’s an example of using this to recursively resize all of the images in a directory:

  1. cd /path/to/original/dir; find | grep -i jpg$ | while read line
  2. do
  3. if [ ! -d "`dirname "../JJ-products-2011-12-19-thumbs/$line"`" ] ; then
  4. mkdir -p "/path/to/new/dir/`dirname "$line"`";
  5. fi;
  6.  
  7. convert "$line" -scale 150x150\> -quality 50% -unsharp 1x3+1+.1 -sampling-factor 1x1 -strip "/path/to/new/dir/`dirname "$line"`/`basename "$line"`";
  8. done

The full manual is available here: http://www.imagemagick.org/script/command-line-options.php#profile and here: http://www.imagemagick.org/Usage/resize/#scale

ImageMagick does an awful lot more than this, so check out the manual.