Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required