Batch Resize Photos with Image Magic

ImageMagic

I’m currently working on migrating a large publishing website form Drupal to WordPress and one of the things that occurred to me was that WordPress generates 3 sizes for each image that’s uploaded into Media Library. However, our Drupal website only contains a single image. To make the media library work nicely in WordPress we’ve decided to resize thousands of images in Drupal to 3 different sizes ready to be consumed by WordPress. The tool I’ve picked is ImageMagic. A wonderful command line image resizing tool that allows you to batch resize photos relatively quickly.

If you are using OS X, you can install image magic by running

brew install imagemagick

or on linux

apt-get install imagemagick

Now you’re ready to batch resize photos. The script below will batch resize photos and group them into 3 directories – small, medium, large. You will need to create small, medium, large directories yourself if you are going to use this script as is.

#!/bin/bash

smallwidth=100
smallheight=100
mediumwidth=300
mediumheight=300
largewidth=1024
largeheight=1024

rm -rf small/*
rm -rf medium/*
rm -rf large/*

for file in *
do
 imagewidth=$(identify -format "%w" "${file}")
 imageheight=$(identify -format "%h" "${file}")
 if [ $imagewidth -ge $imageheight ]
    then
        mogrify -path small/ -resize $smallwidth "${file}"
        mogrify -path medium/ -resize $mediumwidth "${file}"
        mogrify -path large/ -resize $largewidth "${file}"
    else
        mogrify -path small/ -resize x$smallheight "${file}"
        mogrify -path medium/ -resize x$mediumheight "${file}"
        mogrify -path large/ -resize x$largeheight "${file}"
 fi
done

cd small
for file in *
do
        mv "${file}" "${file%.*}-${smallwidth}x${smallheight}.${file##*.}" 2>/dev/null
done
cd ..

cd medium
for file in *
do
        mv "${file}" "${file%.*}-${mediumwidth}x${mediumheight}.${file##*.}" 2>/dev/null
done
cd ..

cd large
for file in *
do
        mv "${file}" "${file%.*}-${largewidth}x${largeheight}.${file##*.}" 2>/dev/null
done

Feel free to use this and modify to your needs. You could further improve this by uploading all images to S3 after you’ve resized them all. You can use this excellent command line S3 client to do that.

Marko