I've had a couple jobs recently that required scripts to automatically manipulate images. I wrote one in PHP, using ImageMagick, and the other was in Perl, also using Image::Magick. I decided I wanted to do some of this sort of stuff on my Mac OS X iBook, but for various reasons wanted to give the GD module a try instead. I set aside an entire afternoon of free time, warned the family to stay clear, and prepared for the coming hours of thrashing in installation hell. Surprisingly, before I could even finish brewing the first cup of coffee, I was done.

Okay, to be completely honest, I had a few unfair advantages. First I had the Darwin Ports package manager installed. This has been a great little tool for me over the months I've used it and I'd highly recommend it. It installs everything under the /opt/local/tree so you won't have to worry about conflicts with existing software. You will, however, want to add that directory to your PATHlist.

Having that already in place, I merely had to type sudo port install gd2to get the libgd libraries all installed for me. That took all of a couple minutes. Then I took advantage of Perl's own package manager CPAN. With /opt/local/bin/in the PATH, and libgd installed, it was another one-liner to get the GD module installed and linked in to the libraries: sudo perl -MCPAN -e'install GD'.

So -- try not to laugh -- the entire procedure took about three minutes and looked like this...

sudo port install gd2
sudo perl -MCPAN -e'install GD'

After drinking that cup of coffee, it's time to test our new module out and make sure it's in working order. Let's do something simple like add a timestamp to an image, printing the date and time it was requested from the webserver across the top.

use CGI qw(header);
use GD;

my $image = new GD::Image('molly.png');

my $timestamp = localtime;

my $gray = $image->colorAllocate(20,20,20);
my $white = $image->colorAllocate(255,255,255);

$image->string(gdSmallFont, 5, 11, $timestamp, $gray);
$image->string(gdSmallFont, 4, 10, $timestamp, $white);

print header('image/jpeg');
print $image->jpeg;

And finally, you can see the results of this script by simply adding an HTML tag pointing to the it, like so: <img src="/cgi-bin/im.cgi" />.