Creating and Drawing Images

For now, let’s start with the simplest possible GD example. Example 9-1 is a script that generates a black-filled square. The code works with any version of GD that supports the PNG image format.

Example 9-1. A black square on a white background (black.php)

<?php
$image = imagecreate(200, 200);

$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);

header("Content-Type: image/png");
imagepng($image);

Example 9-1 illustrates the basic steps in generating any image: creating the image, allocating colors, drawing the image, and then saving or sending the image. Figure 9-1 shows the output of Example 9-1.

A black square on a white background

Figure 9-1. A black square on a white background

To see the result, simply point your browser at the black.php page. To embed this image in a web page, use:

<img src="black.php" />

The Structure of a Graphics Program

Most dynamic image-generation programs follow the same basic steps outlined in Example 9-1.

You can create a 256-color image with the imagecreate() function, which returns an image handle:

$image = imagecreate(width, height);

All colors used in an image must be allocated with the imagecolorallocate() function. The first color allocated becomes the background color for the image[4]:

$color = imagecolorallocate(image, red, green, blue);

The arguments ...

Get Programming PHP, 3rd Edition 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.