O'Reilly logo

Web, Graphics & Perl/Tk Programming by Jon Orwant

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required