A very simple and tiny shellscript for cropping images recursively with Imagemagick on Linux. In my case I am working on a Ruby on Rails website, managing images and its thumbnails with attachment_fu. After some months I decided to convert all user stored thumbnails to a cropped format. This is what this script was for.

#!/bin/bash
#
# very little and tiny shellscript for cropping images
# massively and recursively with Linux and Imagemagick
# Make sure you have Imagemagick installed (ie: try to
# execute "convert" binary)
#
# USAGE: place this script in your images parent directory,
# edit and change the size names and widths
#
# Ivan Belmonte <ivan@ivanhq.net - http://ivanhq.net>

SIZES="icon:48 thumb:120" # change them for your needs
FORMATS="jpg JPG jpeg JPEG gif GIF png PNG"


# remove previously sized files
for SIZE in ${SIZES}; do
  SIZENAME=`echo ${SIZE} | cut -f 1 -d :`
  find . | grep -i _${SIZENAME} | xargs rm -f
done


# start resizing and cropping
for FORMAT in ${FORMATS}; do

  for FILE in `find . | grep ${FORMAT}`; do

    for SIZE in ${SIZES}; do

      SIZENAME=`echo ${SIZE} | cut -f 1 -d :`
      SIZEWIDTH=`echo ${SIZE} | cut -f 2 -d :`
      FILENAME=`echo ${FILE} | sed s/".${FORMAT}"//g`

      convert ${FILE} -resize \
      "${SIZEWIDTH}^>" ${FILENAME}_${SIZENAME}.${FORMAT}

      convert -gravity Center -crop \
      ${SIZEWIDTH}x${SIZEWIDTH}+0+0 \
      ${FILENAME}_${SIZENAME}.${FORMAT} \
      ${FILENAME}_${SIZENAME}.${FORMAT}

    done

  done

done

echo "OK"

# enjoy :-)