Not a Tango, nothing to see here

May 3, 2011

Thumbnails… and lots of them.

Filed under: Linux — Tags: , — antitango @ 7:13 pm

So I needed some thumbnails.  I wanted them created in a subdirectory relative to the location of the image.  For instance, if you have dir/filename.jpg it would scale the image down to a specific width/height and drop it into dir/image_thumbs/filename.thumb.jpg.  I could not find anything to handle this at the filesystem level, so I had to write one myself…  Bash to the rescue!  This script requires ImageMagick and a relatively new version of bash due to globstar.

#!/bin/bash
shopt -s globstar
shopt -s nullglob

thumbsdir=image_thumbs

if [[ $1 = "clean" ]]; then
        find . -name "${thumbsdir}" -type d -exec rm -rfv {} \; || exit 100
        exit
fi
if [[ -z $1 ]]; then
        thumbsdir=image_thumbs
else
        thumbsdir="${1}"
fi

for file in ./**; do
        [[ ! -d "${file%/*}/${thumbsdir}" ]] && mkdir -p "${file%/*}/${thumbsdir}"

        tmp="${file%/*}"
        if [[ ! "${tmp##*/}" = "${thumbsdir}" ]]; then
                if [[ ! -d "${file}" ]]; then
                        destdir="${file%/*}/${thumbsdir}"
                        tmp="${file%.*}.thumb.${file##*.}"
                        destfile="${tmp##*/}"
                        echo -n "Converting \"${file}\" to \"${destdir}/${destfile}\"... "

                        file "${file}" | grep "image data" >/dev/null 2>&1
                        [[ $? = 0 ]] && isimage=1 || isimage=0
                        if [[ ! -f "${destdir}/${destfile}" ]] ; then
                                if [[ ${isimage} = 1 ]]; then
                                        convert -resize 700x700 -auto-orient "${file}" "${destdir}/${destfile}" >/dev/null 2>&1 && echo "Done!" || echo "  Error from ImageMagick!"
                                else
                                        echo "  File is not image"
                                fi
                        else
                                echo "  Exists."
                        fi
                fi
        fi
done
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.