One of the biggest issues on the internet is protecting your media. You could disable right click or try other forms of trickery, but if someone wants your image, they are going to get it somehow. The best way to protect your images is to add a watermark.
You can add a watermark yourself — image by image — or use PHP’s GD library to do it for you automatically. Its a lot easier then you probably think.
All we need from the .htaccess file is to direct any requests (aside from image.php) to image.php to do all the work.
.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !image.php$
RewriteRule (.*) image.php?$1 [L]
</IfModule>
image.php
// set relevant vars
$img = $_SERVER['QUERY_STRING'];
$ext = substr($img, strrpos($img, '.') + 1);
// determine what type of image
switch($ext) {
case 'gif': $src = imagecreatefromgif($img); break;
case 'jpeg':
case 'jpg': $src = imagecreatefromjpeg($img); break;
case 'png': $src = imagecreatefrompng($img); break;
}
$width = imagesx($src);
$height = imagesy($src);
// "flatten" gif images
if($ext == 'gif') {
$tmp = $src;
$src = imagecreatetruecolor($width, $height);
imagecopyresampled($src, $tmp, 0, 0, 0, 0, $width, $height, $width, $height); imagedestroy($tmp);
}
// import transparent watermark
$tmp = imagecreatefrompng('watermark.png');
$png = imagecreatetruecolor($width, $height);
imagesavealpha($png, true);
$trans = imagecolorallocatealpha($png, 0, 0, 0, 127);
imagefill($png, 0, 0, $trans);
imagecopyresampled($png, $tmp, 0, 0, 0, 0, $width, $height, imagesx($tmp), imagesy($tmp));
// combine src and watermark
imagecopy($src,$png,0,0,0,0,imagesx($src),imagesy($src)); imagedestroy($png);
// output
switch($ext) {
case 'gif':
header('Content-Type: image/gif');
imagegif($src);
break;
case 'jpeg':
case 'jpg':
header('Content-Type: image/jpeg');
imagejpeg($src, '', 100);
break;
case 'png':
header('Content-Type: image/png');
imagepng($src);
break;
}
Drop these two files, along with your watermark image, into any directory and any image within the directory will be served up with a watermark
Check out the demo page to view a few examples.
1 Trackback
[...] This post was mentioned on Twitter by Nicholas Patten, Matt Engebregtsen. Matt Engebregtsen said: Add Watermarks to a Directory of Images using PHP's GD library: http://matte.ws/image-watermark [...]