Watermark images using 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 such as subdirectory/image.jpg 

$imagesource =  $_GET[‘path’]; 

$filetype = substr($imagesource,strlen($imagesource)-4,4); 

$filetype = strtolower($filetype); 

if($filetype == “.gif”)  $image = @imagecreatefromgif($imagesource);  

if($filetype == “.jpg”)  $image = @imagecreatefromjpeg($imagesource);  

if($filetype == “.png”)  $image = @imagecreatefrompng($imagesource);  

if (!$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); 





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: 

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s