How to watermark an image in PHP

Watermarking an image in PHP is very easy. If you follow the code below, you can do it in 2 minutes.

<?php

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
//$SourceFile is source of the image file to be watermarked
//$WaterMarkText is the text of the watermark
//$DestinationFile is the destination location where the watermarked images will be placed

//Delete if destinaton file already exists
@unlink($DestinationFile);

//This is the vertical center of the image
$top = getimagesize($SourceFile);
$top = $top[1]/2;
list($width, $height) = getimagesize($SourceFile);

$image_p = imagecreatetruecolor($width, $height);

$image = imagecreatefromjpeg($SourceFile);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

//Path to the font file on the server. Do not miss to upload the font file
$font = ‘arial.ttf’;

//Font sie
$font_size = 16;

//Give a white shadow
$white = imagecolorallocate($image_p, 255, 255, 255);
imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);

//Print in black color
$black = imagecolorallocate($image_p, 0, 0, 0);
imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);

if ($DestinationFile<>”) {

imagejpeg ($image_p, $DestinationFile, 100);

} else {

header(‘Content-Type: image/jpeg’);

imagejpeg($image_p, null, 100);

};

imagedestroy($image);

imagedestroy($image_p);

};

?>

<?php

$SourceFile = ‘image.jpg’;//Source image
$DestinationFile = ‘watermarked/image.jpg’;//Destination path
$WaterMarkText = ‘www.phpHelp.co’;//Watermark text

//Call the function to watermark the image
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

//Display watermarked image if desired
if(file_exists($DestinationFile)){
echo “<img src=\”watermarked/image.jpg\”>”;
echo “<p>The image has been watermarked at ‘”.$DestinationFile.”‘</p>”;
}
?>

Note:

  • This code is being provided to you as a help by http://www.phpHelp.co without any warranty and liability
  • Place all the files in a folder on web server.
  • Do not forget to upload the font file – arial.ttf.
  • Once the image is watermarked, it will be placed in the folder named ‘watermarked’.
  • You might need to give ‘write permission’ or ’777 permission’ to the folder named ‘watermarked’ as the new watermarked image will be written in this folder.

Leave a Reply

Your email address will not be published. Required fields are marked *


2 + = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>