One of the things you can do with PHP's many functions for image handling and manipulation is create an image watermarking class. This will allow you to add a watermark to images, which can be useful for a number of purposes. Keep reading to learn how.
Just to keep things simple, we’ve introduced two helper functions into our application. These functions are narrow in focus, each one performing a very specific task. By using them, however, we are able to clean up the code within our “create_watermark” function. Let’s add them to our class, then we’ll take a look at each:
# average two colors given an alpha
function _get_ave_color( $color_a, $color_b, $alpha_level ) {
# return closest pallette-color match for RGB values
function _get_image_color($im, $r, $g, $b) {
$c=imagecolorexact($im, $r, $g, $b);
if ($c!=-1) return $c;
$c=imagecolorallocate($im, $r, $g, $b);
if ($c!=-1) return $c;
return imagecolorclosest($im, $r, $g, $b);
} # EBD _get_image_color()
Our first function, “_get_ave_color”, accepts two color values, along with our (optional) user-specified alpha level, and returns a weighted average of the colors it has been passed. This function will help us blend the images we have been passed by averaging their colors at overlapping points.
Next, “_get_image_color”, accepts an image object along with red, green, and blue color values. Using a few of the built-in PHP image-manipulation methods, this function then returns the closest available match (to the color specified) that exists within our image object’s color palette.
In order to do this, it checks several things. First, if an exact match can be found, it is returned. If not, it will attempt to allocate a new palette color to match the one specified. If that fails as well, then as a last resort our function will simply return the closest pre-existing color match found within the images palette.
If this seems a little confusing, don’t worry. It will make more sense once we put the pieces together.