Color Handling

The GD library supports both 8-bit palette (256 color) images and true color images with alpha channel transparency.

To create an 8-bit palette image, use the imagecreate() function. The image’s background is subsequently filled with the first color you allocate using imagecolorallocate():

$width = 128;
$height = 256;

$image = imagecreate($width, $height);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);

To create a true color image with a 7-bit alpha channel, use the imagecreatetruecolor() function:

$image = imagecreatetruecolor(width, height);

Use imagecolorallocatealpha() to create a color index that includes transparency:

$color = imagecolorallocatealpha(image, red, green, blue, alpha);

The alpha value is between 0 (opaque) and 127 (transparent).

While most people are used to an 8-bit (0–255) alpha channel, it is actually quite handy that GD’s is 7-bit (0–127). Each pixel is represented by a 32-bit signed integer, with the four 8-bit bytes arranged like this:

High Byte                   Low Byte
{Alpha Channel} {Red} {Green} {Blue}

For a signed integer, the leftmost bit, or the highest bit, is used to indicate whether the value is negative, thus leaving only 31 bits of actual information. PHP’s default integer value is a signed long into which we can store a single GD palette entry. Whether that integer is positive or negative tells us whether antialiasing is enabled for that palette entry.

Unlike with palette images, with true color images the first color you allocate does not automatically ...

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.