Analog clock images with Bash and ImageMagick

Posted by mikael on 2011-07-17 16:39, section: Hacks

A little while back I decided to try creating a script that would generate PNGs of an analog clock so I could run the script using cron and display the images with Geektool, this is the result.

First of all we need three images to assemble into the final clock. Below are the ones I created and used, consider them free to use if you want to.

Background for the clock Hour arm for the clock Minute arm for the clock

Next, put the three images in a directory and create the following script in the directory.

#!/usr/bin/env bash

# Path to ImageMagick convert program
conv="/usr/local/bin/convert -quiet"

# IMPORTANT: Set this to the path where the images and the script reside.
basedir=$HOME"/bin/clock/"

# Time in hours
hourtime=`date "+%H"`
if [ "$hourtime" -gt "12" ]
then
        hourtime=`expr $hourtime - 12`
        # now $hourtime = hours since 12
fi

# Time in minutes
minutetime=`date "+%M"`

# 1 find angle of hour arm
hourasminutes=`expr $hourtime \* 60`
minutessincetwelve=`expr $hourasminutes + $minutetime`
hourangle=`expr $minutessincetwelve / 2`

# 2 find angle of minute arm
minuteangle=`expr $minutetime \* 6`

# 3 combine bg and hour arm
$conv ${basedir}hour_1000x1000.png -virtual-pixel transparent \
+distort SRT "500,500 1.0 $hourangle 500,500" \
-trim ${basedir}bg_1000x1000.png +swap -background none \
-layers merge +repage ${basedir}tmp.png

# 4 combine result of 3 with minute arm
$conv ${basedir}minute_1000x1000.png -virtual-pixel transparent \
+distort SRT "500,500 1.0 $minuteangle 500,500" \
-trim ${basedir}tmp.png +swap -background none \
-layers merge +repage ${basedir}tmpout.png

# 5 add drop shadow
$conv ${basedir}tmpout.png -virtual-pixel transparent \
-background none \( +clone -background none -shadow 30x10+0+0 \) \
+swap -layers merge +repage ${basedir}out.png

If you run this script you should get an image called out.png that looks a lot like the one below (and two images called tmp.png and tmpout.png but if you can't figure out how to modify the script to get rid of them you probably shouldn't be running random scripts from the net anyway). The out.png image is also 40 pixels higher and wider than the source images, if you skip the drop shadow it will be the same size as the source images.

I hope this was useful for someone out there.

Final result
blog comments powered by Disqus