← all posts

Quickly creating thumbnails from the command line

I recently found myself having to create thumbnails for a few images on a static site. The full resolution images were 2-3MB and took quite a few seconds to load from my VPS.

Being more of a developer than a designer, I’m glad that great tools like ImageMagick exist to make command line manipulation of images a breeze.

Specifically, the convert utility lets your resize images and create thumbnails easily.

                
> convert my-image.png -auto-orient -thumbnail 350x350 \
    -unsharp 0x.5 my-image-thumb.png
                
              

It’s as easy as that!

The 350x350 ensures that the thumbnail does not exceed 350px in height or width while still preserving the aspect ratio. To specify other dimensions and ratios, see ImageMagick’s geometry documentation

Helper Function

Although… that’s a lot of syntax to remember and look up.

I wanted to make a helper function to easily create thumbnails anytime. So I came up with the function below, which I just added to my .bash_profile

Using it is a breeze:

                
> thumbify ./pic.jpg
Creating ./pic-thumb.jpg with max dimension 250 px

> thumbify ./pic.jpg 322
Creating ./pic-thumb.jpg with max dimension 322 px
                
              
                
function thumbify {
  YELLOW='\033[0;33m'
  NOCOLOR='\033[0m'

  DEFAULT_SIZE=250
  FILEPATH=$1
  ARG=$2
  SIZE=${ARG:-250}

  USAGE="
    ${YELLOW}
    Create thumbnail images
    Usage:
      thumbify file [dimension]

        file        file to create thumbnail from
        dimension   maximum dimension (in pixels) of height or width. Aspect
                    ratio will be preserved. (Default: $DEFAULT_SIZE px)

    Examples:

       thumbify file.jpg
       thumbify ./path/to/file.jpg
       thumbify file.jpg 350
    ${NOCOLOR}"


  if [ -z "$1" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo -e $USAGE
    return
  fi

  if ! [ -x "$(command -v convert)" ]; then
    echo 'Error: Command `convert` not found. Are you sure ImageMagick is installed?' >&2
    return
  fi

  # Create thumnail filename
  #  ./path/to/file.jpg -> ./path/to/file-thumb.jpg
  filename=$(basename -- "$FILEPATH")
  extension="${filename##*.}"
  thumbname=`echo $FILEPATH | sed "s/.$extension/-thumb.$extension/"`

  # Create thumbnail
  echo "Creating $thumbname with max dimension $SIZE px"
  convert $FILEPATH -auto-orient -thumbnail $SIZEx$SIZE -unsharp 0x.5 $thumbname
}