How to Watermark Images using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Watermark Images using PHP

Post by Tony » Sun Nov 29, 2009 3:59 am

The best way to protect your images is to watermark them. But that can be a real hassle. This script will take any image and automatically add a watermark before it is delivered from the server to the person's browser. The instructions for using this script are in the comment lines at the top of the script.

Code: Select all

<?php
// this script creates a watermarked image from an image file - can be a .jpg .gif or .png file
// where watermark.gif is a mostly transparent gif image with the watermark - goes in the same directory as this script
// where this script is named watermark.php
// call this script with an image tag
// <img src="watermark.php?path=imagepath"> where path is a relative path from the document root - such as subdirectory/image.jpg
$imagesource = $_SERVER['DOCUMENT_ROOT']."/".$_GET['path'];
if (!file_exists($imagesource)) die();
$filetype = strtolower(substr($imagesource,strlen($imagesource)-4,4));
if($filetype == ".gif") $image = @imagecreatefromgif($imagesource); 
if($filetype == ".jpg") $image = @imagecreatefromjpeg($imagesource); 
if($filetype == ".png") $image = @imagecreatefrompng($imagesource); 
if (empty($image)) die();
$watermark = @imagecreatefromgif('watermark.gif');
$imagewidth = imagesx($image);
$imageheight = imagesy($image); 
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
header("Content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
The script centers the watermark, but can easily be modified to place it along any edge if you would prefer a different location. For example removing the "/2" in the $startwidth and $startheight variable calculations will put the watermark in the lower right corner.

You can then make the original images inaccessible if you put the following lines in a .htaccess file in the directory with the images:

Code: Select all

RewriteEngine On
RewriteCond %{REQUEST_URI} !error.gif$
RewriteRule \.(gif|jpg|png)$ /error.gif [L] 
This will redirect any attempt to directly access an image in that directory to the error image specified. Note that the error image is specified on two lines in the .htaccess file. The first line allows the error image to bypass the rewrite.
Post Reply

Return to “PHP & MySQL”