Team LiB
Previous Section Next Section

Basic Image Creation Using GD

To introduce you to the concept of working with images in PHP, let's look at the general technique that is employed when scripting using the GD graphics library. This process can be generalized into the following steps:

Creation of an image "canvas" in memory by creating a new image or by loading an existing image.

Allocation of colors used in the image (if necessary).

Performing of any drawing or other image manipulations necessary on the canvas.

Saving the canvas to a file in a supported image format or streaming the image at runtime to the browser.

Destroying the unneeded canvas in memory.

For the purposes of this chapter, I will generally be creating new canvases for my examples using the PHP imagecreate() function. The syntax of this function is as follows:

imagecreate($width, $height);

The $width and $height parameters are integers specifying the width and height of the canvas to create in pixels. As with all the functions that create a canvas in memory, this function returns a resource representing the canvas or returns false on failure. This resource is the means by which PHP identifies the canvas; it is used throughout all the image manipulation functions and allows you to have multiple canvases in memory simultaneously.

Image canvases are the foundation of almost all the functionality provided by the GD extension. As you will see shortly, image canvases are not always created from scratch, either, but can be created from already existing images.

After a new canvas has been created, it is not yet considered a "valid" image of any type, simply because it does not have any colors associated with it in its palette. Because even the simplest palette image has at least one color, before you can display even a simple single-color image, you must allocate that color in the canvas's palette. This is usually done using the imagecolorallocate() function with the following syntax:

imagecolorallocate($img_r, $red, $green, $blue);

$img_r is the resource representing the canvas on which to allocate the color, whereas $red, $green, and $blue are integers between 0 and 255 (or 0x0 to 0xFF in hexadecimal) for each color. When executed, this function attempts to allocate a new color in the palette with the specified red, green, blue (RGB) values. If the allocation was successful, the function returns an integer index representing the color's location in the palette or 1 if the allocation failed.


As you will see, there is more to allocation of colors than the imagecolorallocate() function. Many functions are available that can help you make the best use of your palette; I will discuss these later.

It is important to note that when you create a new image, the first color allocated to the palette automatically is assigned to the entire image as the background color. Hence, the order in which you allocate colors to your palette has a certain degree of importance.

An alternative to creating a palette-based image is to create a true-color image using the imagecreatetruecolor() function. This function behaves identically to its imagecreate() counterpart, with the obvious difference that the canvas it creates does not rely on a palette of 256 colors. The syntax for this function is identical to that found for imagecreate() as shown next:

imagecreatetruecolor($width, $height);

$width and $height represent the width and height of the canvas to create (in pixels). When you work with true-color images, it is important to note that there is no need to allocate a background color to the palette, as was required with imagecreate(). Instead, all true-color images are automatically created with the background color of black.

Although we have barely scratched the surface of the creation of images using the GD extension, the functions you have been introduced to thus far provide all that is necessary to create a very simple (and boring) image in memory, which can be presented or saved in any of the formats supported by the GD extension on your system. This is accomplished by using one of the image output functions available to you. For the purposes of this chapter, I have elected to use the PNG format for all my images; hence, I will discuss the imagepng() function here. The syntax for this function is as follows:

imagepng($img_r [, $filename]);

$img_r represents the image resource that should be used, and the optional $filename parameter is the filename to write the image to. If no filename is provided, the imagepng() function will send the appropriate headers and output the image directly to the browser. For example, to create a script that renders a simple image using a single color (red), the following can be used:

    $img = imagecreate(200, 200);
    imagecolorallocate($img, 0xFF,0,0);

    header("Content-type: image/png");


Although I have only formally discussed the imagepng() function to output images, the following functions are all available to output the image in other formats (each with a similar functional syntax to the imagepng() function):

image2wbmp() Output an image in WBMP format.

imagejpeg() Output an image in JPEG format.

imagewbmp() Output an image in WBMP format.

imagegd() Output an image in native GD format.

imagegd2() Output an image in native GD2 format.

Although the first and second parameters of each of the preceding functions are identical to the imagepng() function, they each have additional optional parameters that can be used, if desired. If you would like details about these functions, consult the PHP manual for more information.

When executed, this simple script renders a blank image with the background color of 0xFF0000 (red) that is 200 by 200 pixels in size. If we had wanted to save this image to the file system, the second parameter $filename could have been provided to the imagepng() function, providing a filename to write the PNG image to.

Retrieving Image information

Now that you have had a proper introduction to the ways that an image canvas can be created, let's take a look at the types of functions that can be used to gather information about those canvases (and consequently the images they represent). The first of these functions are the imagesx() and imagesy() functions, which return the width and height (in pixels), respectively, of a given image resource. The syntax for these functions is as follows:


$img_r is the image resource. Although I will not be using these functions much at the start of this chapter (because the size of the canvas will generally be known early on), as I begin working with images loaded from the file system, these functions become quite important.


For a non-GD method of retrieving the size of an image, see the getimagesize() function in the "Other Graphics Functions" section.

As you will see later in this chapter, another important piece of information required about a image loaded from the file system is the nature of its palette. Because certain operations are best performed on true-color images, the GD extension provides the imageistruecolor() function with the following syntax:


$img_r is the image resource. When executed, this function will return a Boolean true if the provided image resource is true color, or false otherwise.

Another extremely useful function provided by the GD extension is the gd_info() function. Because the GD extension relies on so many different external libraries, the graphic file formats, font formats, and so on that are available can change drastically from one version of PHP to the next. To help your scripts determine the capabilities of the GD extension being used, this function is provided. The syntax for this function is as follows:



The gd_info() function differs from the phpinfo() function in the sense that it does not directly output anything from the browser. Rather, it is returned as a return value.

When executed, this function will return an associative array describing the capabilities of the GD extension being used. The information available in this array and its meaning can be found in the following table:

Array Key


GD Version

The version of GD being used. (string)

FreeType Support

Boolean indicating whether FreeType is enabled.

FreeType Linkage

A string describing how FreeType was linked into PHP. Possible values are with freetype, with TTF library, or with unknown library.

T1Lib Support

A Boolean indicating whether T1LIB (PostScript Fonts) are enabled.

GIF Read Support

A Boolean indicating whether GD can read GIF files.

GIF Create Support

A Boolean indicating whether GD can create GIF files.

JPG Support

A Boolean indicating whether JPEGs are supported.

PNG Support

A Boolean indicating whether PNG images are supported.

WBMP Support

A Boolean indicating whether WBMP images are supported.

XBM Support

A Boolean indicating whether XBMP images are supported.

This information can be used by your script to determine whether it is compatible with the capabilities of the GD extension, or whether it will allow your script to work around those incompatibilities.

Another method of determining the capabilities of the GD extension can be found in the imagetypes() function. If you are concerned only with PHP's capability to work with a specific image type, this function is a better choice than gd_info(). The syntax for this function is as follows:


When executed, this function returns a bit-field constructed using the following: IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP (each constant is bitwise or'd together). To use this informationfor instance, to test whether JPEGs are supportedsimply bitwise and the desired constant with the result of the function:

    $supported = imagetypes();
    if($supported & IMG_JPG) {
              echo "Jpegs are supported in this GD version";
    } else {
              echo "Jpegs are not supported.";

    Team LiB
    Previous Section Next Section