18.7 Making a GIFPNG Transparent


18.7 Making a GIF/PNG Transparent

You want to make a GIF or PNG stream transparent. (JPEG doesn't support transparency.)

Technique

Use the ImageColorTransparent() function to make the background color transparent:

 <?php header("Content-type: image/png"); $im = ImageCreate(100, 20); $bgcolor = ImageColorAllocate($im, 255, 255, 255); $bgcolortrans = ImageColorTransparent($im, $bgcolor); $black = ImageColorAllocate($im, 0, 0, 0); ImageString($im, 2, 5, 5, "Hello World"); ImagePng($im); ImageDestroy($im); ?> 

Comments

When you set a color to be transparent it means that color morphs into whatever the background color is. For example, assume that you have set the color gray as the transparent color for an image. When you put that image on a red background, every occurrence of that gray color becomes the red color of the background.

If you want to see what color is transparent for a specified image, simply use the ImageColorTransparent() function with only one argument like so:

 <?php $im = ImageCreateFromPng('tst.png'); $trans_color = ImageColorTransparent($im); $rgb_col = ImageColorsForIndex($trans_color); echo "The transparent color has a red value of {$rgb_col['red']}"; echo "a green value of {$rgb_col['green']} and a blue value of "; echo $rgb_col['blue']; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net