Tuesday, June 21, 2011

Using a transparent PNG image as watermark in PHP

Sure there are plenty of scripts on the internet that does this thing ... but very few explain this.


Let's use this function:
function watermark($jpgimage, $pngimage){
        $image= imagecreatefromjpg($jpgimage);
        $watermark = imagecreatefrompng($pngimage);

        $ww = imagesx($watermark);
        $wh = imagesy($watermark);
       
        $iw = imagesx($image);
        $ih = imagesy($image);
       
        // watermark position
       $x = ( $iw - $ww ) / 2;
       $y = ( $ih - $wh ) / 2;

        imagealphablending( $image, true);
       
        imagecopyresampled($image, $watermark, $x, $y, 0, 0, $ww, $wh, $ww, $wh);
   
        imagealphablending($image, false);
        imagesavealpha($image, true);
        return $image;
}

This function puts a PNG watermark on a JPG picture while saving the alpha channel, and returns an image resource.

To do this, we first create an image resource from the jpg image and another one from the png(the watermark).
       $image= imagecreatefromjpg($jpgimage);
       $watermark = imagecreatefrompng($pngimage);
After that, we take the images x and y sizes and calculate the watermark position.
        $ww = imagesx($watermark);
        $wh = imagesy($watermark);
       
        $iw = imagesx($image);
        $ih = imagesy($image);
       
        // watermark position
       $x = ( $iw - $ww ) / 2;
       $y = ( $ih - $wh ) / 2;

Then, we set the blending mode to true and add the watermark:
        imagealphablending( $image, true);
       
        imagecopyresampled($image, $watermark, $x, $y, 0, 0, $ww, $wh, $ww, $wh);
Finally, we set the blending mode false and save the alpha channel information for transparency:
        imagealphablending($image, false);
        imagesavealpha($image, true);
That's it. We return the image resource for further manipulation.

No comments:

Post a Comment