Friday, June 21, 2019

Add Water Mark to Image in PHP

Hello

Today i saw you how to add watermark image to your image  with small and simple php script. If you have image based website than it is possible that someone copied your images and misuse it. So avoid to this, i suggest to implement this. 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.


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

$stamp is your watermark png file. $im is your actual jpg image file.

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

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


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

Copy the stamp image onto our photo using the margin offsets and the photo width to calculate positioning of the 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')
                   or
 addWatrmark($im, $stamp)

No comments:

Post a Comment