Page 564 - Beginning PHP 5.3
P. 564
Part III: Using PHP in Practice
First you need to retrieve the color index of the white color in the image. You have a number of ways to
do this. You can use the imagecolorat() function to retrieve the palette index of the color at an exact
pixel location:
$white = imagecolorat( $myCopyright, $x, $y );
Alternatively, you can use imagecolorexact() , passing in the RGB values of the color to retrieve from
the palette:
$white = imagecolorexact( $myCopyright, $red, $green, $blue );
The only drawback to the latter approach is that if the color does not exist in your image ’ s color palette,
the function won ’ t return a valid color index.
Earlier, you saved your copyright image as an 8 - color PNG. This ensures that you have a small palette to
work with and that the white background of your image is uniform throughout the image. If you ’ d
saved the image as a JPEG with millions of colors, you might have created slight variations in the white
background, making it very difficult to pinpoint the white that you wanted to be transparent. By saving
the image as a PNG with a small number of colors, you avoid this issue.
So you can go ahead and use the imagecolorexact() function to return the color index of the white.
Once you have the color index, you can use the imagecolortransparent() function to make that color
transparent in the image. The function takes two parameters: the image resource and the color index to
make transparent.
Add the following two highlighted lines of code at the appropriate place in the watermark.php script
you created earlier:
$destY = ($destHeight - $srcHeight) / 2;
$white = imagecolorexact( $myCopyright, 255, 255, 255 );
imagecolortransparent( $myCopyright, $white );
imagecopy( $myImage, $myCopyright, $destX, $destY, 0, 0, $src width,
$srcHeight );
Now the script ’ s output (see Figure 17 - 19) looks more promising.
526
9/21/09 2:48:44 PM
c17.indd 526 9/21/09 2:48:44 PM
c17.indd 526