Watermark images with mod_rewrite

Below is how I have watermarked images excluding thumbnails with the text ".thumb." and ".highlight." in the name of the image files.

Contents of ".htaccess" :

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !\.thumb\.|\.highlight\.
RewriteRule ^.*[Jj][Pp][Gg]$|.*[Gg][Ii][Ff]$|.*[Pp][Nn][Gg]$ watermark.php?%{REQUEST_FILENAME}

Contents of "watermark.php" :

<?php

// watermark.gif should have a transparent background.
$watermark = "watermark.gif";
$image = $QUERY_STRING;

if (empty($image)) die();

if (!file_exists($image)) {
   header("404 Not Found");
   echo "File Not Found."; die();
}

$outputType = getFileType($image);

watermark($image, $watermark, $outputType);

/**
   Outputs the image $source with $watermark in the lower right corner.
   @param $source the source image
   @param $watermark the watermark to apply
   @param $outputType the type to output as (png, jpg, gif, etc.)
                      defaults to the image type of $source if left blank
*/
function watermark($source, $watermark, $outputType="") {
   $sourceType = getFileType($source);
   $watermarkType = getFileType($watermark);

   if (empty($outputType)) $outputType = $sourceType;
   if ($outputType == "gif") $outputType = "png"; // Okay to remove
   header("Content-type:image/$outputType");

   // Derive function names
   $createSource = "ImageCreateFrom".strtoupper($sourceType);
   $showImage = "Image".strtoupper($outputType);
   $createWatermark = "ImageCreateFrom".strtoupper($watermarkType);

   // Load original and watermark to memory
   $output = $createSource($source);
   $logo = $createWatermark($watermark);
   ImageAlphaBlending($output, true);

   // Find proper coordinates so watermark will be in the lower right corner
   $x = ImageSX($output) - ImageSX($logo);
   $y = ImageSY($output) - ImageSY($logo);

   // Display
   ImageCopy($output, $logo, $x, $y, 0, 0, ImageSX($logo), ImageSY($logo));
   $showImage($output);

   // Purge
   ImageDestroy($output);
   ImageDestroy($logo);
}

function getFileType($string) {
   $type = strtolower(eregi_replace("^(.*)\.","",$string));
   if ($type == "jpg") $type = "jpeg";
   return $type;
}
?>

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

grayscale/alpha images

If using ImageCreateFromPng,PHP and GD do not recognize grayscale/alpha images.

So if you use grayscale images with transparency between 0% and 100%, then save the image as RGB.

Comment