Last updated on November 20, 2017
One of the most common approaches to brand/protect images is watermarking. Here I would like to show you how to use PHP to add a watermark to images. PHP uses its GD library to write text on images using true type fonts.
To add a watermark, you need an image and any font with extension ttf. For example, I will use “arail.ttf” in my tutorial. Image type can be jpg / jpeg, png, gif, wbmp
.
Function to Watermark
Below function will add watermark on images and this function accepts two parameters images path and watermark text.
function createWatermarkOnImage ($imagePath, $waterMarkText){ header ("Content-type: image/jpeg"); $font = 4; $width = imagefontwidth($font) * strlen($waterMarkText) ; $height = imagefontheight($font) ; $image = imagecreatefromjpeg($imagePath); $x = imagesx($image) - $width ; $y = imagesy($image) - $height; $backgroundColor = imagecolorallocate ($image, 255,255,255); $textColor = imagecolorallocate ($image, 0,0,0); imagestring ($image, $font, $x, $y, $waterMarkText, $textColor); imagejpeg($image); }
How to use
As I mentioned above, this function accepts two parameters; image path, and watermark text.
createWatermarkOnImage ('20160514_212931.jpg', 'zueebi');