Add Water Mark to Image in PHP

Do you have a image based website and you are worry for stealing you images then in this tutorial I am going to share simple PHP script which add watermark on your images. Using PHP GD library you can do any type of image merging and image alteration. It is very useful library so we’ll use this library to add simple water mark/logo of your company on image dynamically using PHP GD library.

Load the stamp and the photo to apply the watermark to

$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

Set the margins for the stamp and get the height/width of the stamp image

$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

Copy the stamp image onto our photo using the margin offsets and the photo width to calculate positioning of the stamp.

imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

Using header content type generate the final output

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);



addWatermark() : using below function and pass your watermark and actual image path to generate image with water mark.

function addWatrmark($image, $waterMark) {
$stamp = imagecreatefrompng($waterMark);
$im = imagecreatefromjpeg($image);
 
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
 
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
 
}

Call the above function

 addWatrmark('photo.jpeg', 'stamp.png')

Posted in PHP