Color Handling

Color support improved markedly between GD 1.x and GD 2.x. In GD 1.x there was no notion of the alpha channel, color handling was rather simple, and the library supported only 8-bit palette images (256 colors). When creating GD 1.x 8-bit palette images, you use the ImageCreate( ) function, and the first color you allocate using the ImageColorAllocate( ) function becomes the background color.

In GD 2.x there is support for true color images complete with an alpha channel. GD 2.x has a 7-bit (0-127) alpha channel.

To create a true color image, use the ImageCreateTrueColor( ) function:

$image = ImageCreateTrueColor(width, height);

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

$color = ImageColorResolveAlpha(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. ...

Get Programming PHP 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.