Sample GD Applications

In the larger scheme of things, there are some applications for which GD is best equipped, and some for which you may want to use ImageMagick, a more specialized tool like GD::Graph, or the Gimp. Three application areas where GD shines are:

  • Images that require simple drawing commands

  • Simple images created from user input

  • Situations where the small size of the gd library is an advantage

The first part of this chapter explores these three application areas in more detail. The remainder is a more detailed description of the GD methods and constants.

Simple Drawing: Hello World

The first example will show how to draw simple text and shapes, in this case, “Hello World” in a rectangle on a random field of red polka dots (see Figure 2-1). With GD you have the option of creating 24-bit or 8-bit color images. In both cases you will allocate colors in the image the same way, with the colorAllocate( ) method. By default, GD will create 8-bit indexed PNGs, which are limited to 256 colors but will end up being smaller than 24-bit images. Use the trueColor( ) method to work on a 24-bit image, or trueColorToPalette( ) to convert a 24-bit image to an 8-bit image.

Hello world in GD
Figure 2-1. Hello world in GD

If you are not reading in an image from a previously created file, use the new( ) method to create a new Image object. The format of this image will be determined upon output, based on the output ...

Get Perl Graphics 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.