Chapter 26. GD and L-Systems

Jason Reed

(Or, how to see plants on your computer without getting soil on the keyboard.)

In GD-Graph3d, you learned how Perl could create three-dimensional graphics. Naturally, Perl is quite comfortable with two-dimensional images as well. Lincoln Stein’s GD module (based on Thomas Boutell’s gd library and available from the CPAN) makes it possible to import, manipulate, and even generate GIFs from the comfort of your very own Perl. In this article, we’ll use GD to create images of plants using mathematical constructs called L-systems.

GD

Using GD is straightforward: all that’s necessary to create a GIF suitable for displaying on a web page is a GD::Image object, some colors, and a few drawing commands. It takes only six lines of code to produce a lone brown dot on a white background, a work surely worth millions to a sufficiently avant-garde patron of the arts:

#!/usr/bin/perl

use GD;

$im   = new GD::Image(100,100);
$white = $im->colorAllocate(255, 255, 255);
$brown = $im->colorAllocate(128,   0,   0);

$im->setPixel(42, 17, $brown);

open (OUT, ">masterpiece.gif") or die $!;
print OUT $im->gif();

Here we create an image 100 pixels square and allocate two colors. GIFs use color tables (in particular, a 256-color palette) so it’s necessary to specify in advance which colors are to be used. The colors themselves are specified by their red, green, and blue components, which range from 0 to 255.

The dot is then drawn with setPixel, 42 pixels to the right of the edge ...

Get Web, Graphics & Perl/Tk Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.