Tag Archives: gd

Transparent tiled watermark using GD with PHP

This is a basic method for dynamically adding tiled watermarks to images on your site.  It uses the .htaccess file to give the images to the PHP script which returns the image plus watermarking.

1) Create the image you want to be the watermark as a png with the opacity you want to be used (we’re not lowering the opacity later), and make sure to add extra space around the image according to how big you want the tiles.

2) Add this script to your site as watermark.php:

<?php

$watermark = imagecreatefrompng('/path/to/your/watermark.png');
$imagesrc = '/path/to/image/' . $_GET['src'];
$type = mime_content_type($imagesrc);
switch($type){
  case 'image/jpeg':
    $image = imagecreatefromjpeg($imagesrc);
    break;
  case 'image/png':
    $image = imagecreatefrompng($imagesrc);
    break;
  case 'image/gif':
    $image = imagecreatefromgif($imagesrc);
    break;
  default:
    $image = null;
}
if($image){
  # set dimensions
  $image_width = imagesx($image);
  $image_height = imagesy($image);
  imagealphablending($watermark, TRUE);

  # create the tile and overlay
  imagesettile($image,$watermark);
  imagefilledrectangle($image,0,0,$image_width,$image_height,IMG_COLOR_TILED);

  # output image
  header('content-type: image/jpeg');
  imagejpeg($image);

  #clean up
  imagedestroy($image);
  imagedestroy($watermark);
}


?>

3) Add rewrite rules in .htaccess.  Notice the $_GET[‘src’] in the script above; we need to hand this variable to the script.  In this example, anything in my gallery folder, or with the filename starting with wmark- will be passed to the script:

RewriteRule ^(.*)wp-content/uploads/wmark-(.*) $1path/to/watermark.php?src=wp-content/uploads/wmark-$2
RewriteRule ^(.*)wp-content/uploads/image-gallery/main_gallery/(.*) $1path/to/watermark.php?src=wp-content/uploads/image-gallery/main_gallery/$2

# If you want to exclude a particular image (excludeme.jpg), add this ABOVE the other rules.  The [L] tells it to ignore other rules
RewriteRule ^wp-content/uploads/excludeme\.jpg$ - [L]

The script will only handle jpg/gif/png file types; if it’s possible that your rewrite rules will pass any other file types to the script, make sure to use (.*\.(gif|jpg|jpeg|png)) if it’s possible instead of just the basic (.*) in your rewrite rules.