watermark an image in php

Tuesday 15th January 2008 11:03 PM

TAGS: PHP, watermark

Occasionally when uploading your own photos, or artwork, or even if you run a site that hosts images and you wish to mark them, watermarking can be a useful technique. The aim is to simply overlay an unobtrusive graphic over your source image, I find white text, with a black shadow seems to work the best on both light and dark source images.

It's rather easy in PHP and GD2, and as a bonus we can use a PNG image with alpha transparancy as the "watermark" image, which means proper antialiasing on text, and dropshadows are possible!

You'll need a source JPG image, and also a small watermark image - the script below is well commented so you can see how each step works, simply change the first two variables to point to your image files on the server.

An example using my setup below can be found here (water mark is in the bottom right corner).

/* setup the source file and watermark */
$sourceImg    'beach_large.jpg';
$watermarkImg 'watermark.png';
/* create source file with alphablending */
$image imagecreatefromjpeg($sourceImg);

/* create watermark holder */
$watermark imagecreatefrompng($watermarkImg);
/* get image and watermark dimensions */
$width      imagesx($image);
$height     imagesy($image);

$wmWidth    imagesx($watermark);
$wmHeight   imagesy($watermark);

/* caclulate where to place watermark */
$xPos $width $wmWidth;
$yPos $height $wmHeight;
/* Copy the watermark to the top right of original image */

/* output image directly to browser */
header("Content-Type: image/jpeg");

Comments on this article:

I love feedback and comments, be the first!

Add Comment:

Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.

netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).