How to add watermark to images on the fly using PHP

Watermarks on images are used to protect copyright, promote and advertise or to make your site look cool

If you are the only person uploading images on your website then any photo editing tool can help; however, if you have visitors or members who upload images, you may need an online module to automatically add the watermarks to such images.

The Imagecopy function in PHP is just the thing you need. This function takes two images and places one over the other, thereby providing the watermark effect. 

Positioning the watermark is a key decision. you would definitely not want to block the key parts of the image. Most sites prefer to keep the watermarks positioned at the bottom right while others prefer to place it randomly on the image. Keep in mind that the watermark image should be transparent so that it does not block vital parts of the image.

Here is the script which places the watermark at a static bottom right location on the image

<?php

$mask = imagecreatefrompng('images/watermark.png');

imagealphablending($image, 1);

imagealphablending($mask, 1);

$nx = $ow - 205;

$ny = $oh - 75;

imagecopy($image, $mask, $nx,$ny,0,0,200,70);

?>

In the above example, $mask is the watermark image, $image is the image on which the watermark will be placed, $ow is the width of the image and $oh is the height of the image.

The size of the watermark is 200 by 70 and thus we subtract 205 and 75 from the image width and height to get the static location at the bottom right of the image.

The same script with a little modification can place the watermark at a random position.

Here is the modified script:

<?php

$mask = imagecreatefrompng('images/watermark.png');

imagealphablending($image, 1);

imagealphablending($mask, 1);

$nx = rand(3,$ow-205);

$ny = rand(3,$oh-75);

imagecopy($image, $mask, $nx,$ny,0,0,200,70);

?>

By adding the rand() function, the value for $nx and $ny will change upon every executing and thus placing the watermark at random position.