Tuesday, September 6, 2011

PHP: Watermark an Image

I recently came across a project in which I had to use text overlay to watermark an image with PHP GD. As it was an interesting project, therefore, I decided to share the technique.


$text = "© Copyright 2011"; // Text you will like to place as a watermark.
$file = "images/jpg/image1.JPG"; // path to actual image with full filename (in this case image1.JPG)
    $filew = 'image2'.'JPG'; // intended name of the new image file with watermark enabled
    $dim = getimagesize($file); // function to get dimensions of our original image
    $imagewidth  = $dim[0]; // get the width of the original image
    $imageheight = $dim[1]; // get the height of the original image
    $image = imagecreatefromjpeg($file); //create a new resource from our original image
    $black = imagecolorallocate($image, 0, 0, 0); // color of the copyright text to place on the image
    $grey = imagecolorallocate($image, 128, 128, 128); // I used the grey color to create a shadow
    $font = 'arial.ttf'; // font file. I copied the arial.ttf in the root folder. Use the full path to the file.
    imagettftext($image, 12, 0, 5, 20, $black, $font, $text); // function to copy text on the image.
    imagettftext($image, 12, 0, 6, 21, $grey, $font, $text); // function to copy text to create shadow
    $fpath = "_stamped/"; // my new path for the altered image
    $filec = $fpath .$filew; // create a full new path for the altered image
    imagejpeg($image, $filec ); // copy the image to the new path
    imagedestroy($image); // free the memory

In order to use it in your HTML, use the following code:
echo "<p><img class='image' src=\"$filec\"></p>";

Output Result will be quite similar to that as follows:


No comments:

Post a Comment

From the Web