Web Info and IT Lessons Blog...

Monday 11 May 2015

Watermark Images in PHP

The previous lesson of PHP Lessons Series was about a simple captcha in php and in this lesson we will learn to watermark images in PHP.

Watermark Images in PHP

We need two images for watermarking, one that needs to be watermarked and the other needed to watermark the first one with. A simple php script for watermarking a source image with watermark image is given below:

Watermark1


<?php
header('Content-type: image/png');

$waterMark=imagecreatefrompng('informationbitz.png');
$waterMarkWidth=imagesx($waterMark);
$waterMarkHeight=imagesy($waterMark);

$sourceImage=imagecreatefromjpeg('example.jpeg');
$sourceImageWidth=imagesx($sourceImage);
$sourceImageHeight=imagesy($sourceImage);

imagecopy($sourceImage,$waterMark,0,0,0,0,$waterMarkWidth,$waterMarkHeight);
imagepng($sourceImage);
imagedestroy($sourceImage);
?>

In the above php script we have used imagecopy() function to watermark the source image($sourceImage) with the watermark image($waterMark). The first argument passed in the imagecopy() function is the source image, second argument is the watermark image, third argument is the starting x-position of the watermark image, fourth argument is the starting y-position of the watermark image, fifth argument is the margin-x of the watermark image, sixth argument is the margin-y of the watermark image, seventh argument is the width of watermark image and eighth argument is the height of the watermark image. As you can see the starting x and starting y positions of the watermark image in the above example are both equal to zero, that is why the watermark appears on the top left corner of the source image. We can move the watermark to the bottom right corner by changing the values of starting x and y positions of the watermark image. An example php script of the watermark appearing on the bottom right corner of the source image is given below:

Watermark2


<?php
header('Content-type: image/png');

$waterMark=imagecreatefrompng('informationbitz.png');
$waterMarkWidth=imagesx($waterMark);
$waterMarkHeight=imagesy($waterMark);

$sourceImage=imagecreatefromjpeg('example.jpeg');
$sourceImageWidth=imagesx($sourceImage);
$sourceImageHeight=imagesy($sourceImage);

$srcX = $sourceImageWidth - $waterMarkWidth;
$srcY = $sourceImageHeight - $waterMarkHeight;

imagecopy($sourceImage,$waterMark,$srcX,$srcY,0,0,$waterMarkWidth,
$waterMarkHeight);
imagepng($sourceImage);
imagedestroy($sourceImage);
?>

Stay tuned for more lessons...

No comments:

Post a Comment