Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

15.7. Getting and Setting a Transparent Color

Problem

You want to set one of an image’s colors as transparent. When the image is overlayed on a background, the background shows through the transparent section of the image.

Solution

Use ImageColorTransparent( ) :

$color = ImageColorAllocate($image, $red, $green, $blue);
ImageColorTransparent($image, $color);

Discussion

Both GIFs and PNGs support transparencies; JPEGs, however, do not. To refer to the transparent color within GD, use the constant IMG_COLOR_TRANSPARENT. For example, here’s how to make a dashed line that alternates between black and transparent:

// make a two-pixel thick black and white dashed line
$style = array($black, $black, IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT);
ImageSetStyle($image, $style);

To find the current transparency setting, take the return value of ImageColorTransparent( ) and pass it to ImageColorsForIndex( ) :

$transparent = ImageColorsForIndex($image, ImageColorTransparent($image));
print_r($transparent);
Array
               (
                   [red] => 255
                   [green] => 255
                   [blue] => 255
               )

The ImageColorsForIndex( ) function returns an array with the red, green, and blue values. In this case, the transparent color is white.

See Also

Documentation on ImageColorTransparent( ) at http://www.php.net/imagecolortransparent and on ImageColorsForIndex( ) at http://www.php.net/imagecolorsforindex.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata