Tag Archives: htaccess

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:


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

  # create the tile and overlay

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

  #clean up


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.