HTML
Using PHP GD To Add Watermark To Images
March 28, 2010
0

In this example, we will be adding a watermark (logo) into an image using PHP and GD library. For introduction to PHP GD, visit this post: /blog/2010/03/using-php-gd-to-create-images/

This is the logo image that I will be using:

This logo is a PNG file with alpha channel. With transparent images, using PNG is better than using GIF, but older version of Internet Explorer (version 6) doesn’t support transparent PNGs. Of course, depending on your needs, some watermark does not need transparency at all and in that case PNG is recommended since it’s not limited to 256 colors like GIFs and compressed better than most JPGs.

This is the original image, before the logo is embedded.

To position the logo, you will need to get the image dimensions using imagesx($image) and imagesy($image) functions. In the example below, I am positioning the logo in the bottom right.

<?php
   // Load the image where the logo will be embeded into
   $image = imagecreatefromjpeg($_GET['imageURL']);


   // Load the logo image
   $logoImage = imagecreatefrompng("logo.png");
   imagealphablending($logoImage, true);

   // Get dimensions
   $imageWidth=imagesx($image);
   $imageHeight=imagesy($image);

   $logoWidth=imagesx($logoImage);
   $logoHeight=imagesy($logoImage);

   // Paste the logo
   imagecopy(
      // destination
      $image,
      // source
      $logoImage,
      // destination x and y
      $imageWidth-$logoWidth, $imageHeight-$logoHeight,
      // source x and y
      0, 0,
      // width and height of the area of the source to copy
      $logoWidth, $logoHeight);

   // Set type of image and send the output
   header("Content-type: image/png");
   imagePng($image);

   // Release memory
   imageDestroy($image);
   imageDestroy($imageLogo);
?>
  • Note that if the logo contains transparency, this line is required: imagealphablending($logoImage, true); otherwise the output will not have transparency.
  • To automate the process of adding watermark, there are ways to do RewriteCond whenever the server is fetching an image so that it automatically call the PHP script to embed the watermark. The following post might help on that topic:
    http://www.tiglo.co.uk/part-1-preventing-image-hotlinking-web-scrapers-and-referral-spam/

  • Finally, here’s the PHP GD reference: http://www.php.net/manual/en/refs.utilspec.image.php
    There are client-side scripting alternatives to adding watermark with images. However, with client-side scripts, it is always possible for users to retrieve the original image from the cache or by right clicking and Save As. If you are interested, HTML5 is a possible alternative. Another alternative is using CSS as described here.