HowTo – Watermark Your Images With PHP And GD

Filed under: Site Management

phpSome websites have a large value placed on the images they display.

They could be photographs taken by a professional photographer or they could be products that they want to protect.

Although all images are copyright protected and placing watermarks is a relatively simple task in GIMP or Photoshop you may have reason to need a online tool to mark your images when you are uploading them.

This HowTo will cover the watermarking process and you will need to apply it to your image upload code.

The first thing you will need to do is make your watermark image. The best formats include jpeg or png files because they provide a nice dither. Gif files can also be used if you need transparency but your version of GD may not support Gif Files.

It is probably not a good technique to apply GD Generated watermarks to each image when they are viewed. This would take a large amount of resources. It is best to apply the watermark and save the image.

imagecopymerg() will be our friend

We will first define the images to be merged and set the transparency level and location of the resulting watermark. Then we will load each image and merge them.

//Define the image location and variables 
$imagelocation = 'uploads/myphoto.jpg';
$watermarklocation = 'watermark.png';
$opacity = 25; // value of the watermark
$margin = 5; // offset of the watermark

//Load the images 
$image = imagecreatefromjpeg($imagelocation);
$watermark = imagecreatefrompng($watermarklocation);

//Read the dimensions of our images 
list($image_width, $image_height) = getimagesize($imagelocation);
list($watermark_width, $watermark_height) = getimagesize($watermarklocation);

//Calculate the location the watermark will be placed 
$watermark_x = $image_width - $watermark_width - $margin;
$watermark_y = $image_height - $watermark_height - $margin;

//Merge the Two files to make the final image 
imagecopymerge($image, $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height, $opacity);

//Print the header, print The Final image, unload from memory 
header("Content-type: image/jpeg");
imagejpeg($image, null, 100);
imagedestroy($image);
imagedestroy($watermark);

Obviously if you need to do this on the fly you will need to apply this code to your image uploader.  As you can see we used both JPEG and PNG files and you can read in and output which ever format you need. JPEG files are still probably the best choice for the final image but PNG files for transparent lettering or logos works well.

For more information about the use of GD to create Watermarks on your images go to the PHP.Net documentation site.

http://us3.php.net/manual/en/function.imagecopymerge.php