[Tip/Trick] PHP Auto Image Watermarking

Status
Not open for further replies.

Juo

Active Member
211
2009
0
0
If you’ve ever wanted to watermark images on your website, this neat script will be just what you’re looking for.

The watermark image is held in a separate file, rather than having to actually edit each image with your watermark, save and upload, this script will serve the watermark to the user on the image as and when its requested.

watermark.png

Warez-DnB PNG​

I like this approach to watermarking because no only is it much easier than editing each picture individually it also means with FTP access you still have an original image intact without the watermark. Only users connecting via HTTP will see the watermarked version.

This also allows for ultimate flexibility, if for whatever reason you decide to change the site logo, its as simple as replacing one image file and every image hosted will have the new watermark.

Save this simple PHP script below as watermark.php
Code:
<?php
	$path = $_SERVER['DOCUMENT_ROOT'].$_SERVER['REQUEST_URI'];
	$image = imagecreatefromstring(file_get_contents($path));

	$w = imagesx($image);
	$h = imagesy($image);

	$watermark = imagecreatefrompng('watermark.png');
	$ww = imagesx($watermark);
	$wh = imagesy($watermark);

	imagecopy($image, $watermark, $w-$ww, $h-$wh, 0, 0, $ww, $wh);

	eregi('\.(gif|jpeg|jpg|png)$',$path,$regs);
	switch( $regs[1] ) {
		case 'gif':
			header('Content-type: image/gif');
			imagegif($image);
		break;
		
		case 'jpg':
		case 'jpeg':
			header('Content-type: image/jpeg');
			imagejpeg($image);
		break;
		
		case 'png':
			header('Content-type: image/png');
			imagepng($image);
		break;
	}
	exit();
	
?>

Next upload the watermark.php file and image into the directory you want watermarking to take place.

The final step is an edit to the .htaccess file (or to make a new one in the directory images are to be served from) and add the following.

Code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule \.(gif|jpeg|jpg|png)$ watermark.php [QSA,NC]
Just to review if you wanted to use the directory /images/ you should now have
/images/watermark.php
/images/watermark.png
/images/.htaccess


Now start uploading some images and everything should be working

Examples

Before
espresso.jpg


After
espresso.jpg


Enjoy :)
 
1 comment
Status
Not open for further replies.
Back
Top