There are several situations when we need to add watermark to the image to protect copyrights and authorship of those images. But doing this task using some application isn’t a smart option. I am going to tell you a very simple and sophisticated way to generate the images with watermark dynamically using PHP.
PHP GD library is really a helpful tool to perform some image related tasks. We are going to use this library to add watermark to a bunch of images in this tutorial.
In this tutorial, we are going to add a watermark to all images in a folder dynamically and saving all those images in a different folder.
Here is the PHP code:
<?php //Source folder where all images are placed $source="source"; //Destination folder where all images with watermark will be copied $destination="destination"; //Creating an image object of watermark image $watermark=imagecreatefrompng("watermark.png"); //Margin of watermark from right and bottom of the main image $margin_right=10; $margin_bottom=10; //Height ($sy) and Width ($sx) of watermark image $sx=imagesx($watermark); $sy=imagesy($watermark); //Get list of images in source folder $images=array_diff(scandir($source), array('..', '.')); foreach($images as $image){ //Create image object of main image $img=imagecreatefromjpeg($source.'/'.$image); //Copying watermark image into the main image imagecopy($img, $watermark, imagesx($img) - $sx - $margin_right, imagesy($img) - $sy - $margin_bottom, 0, 0, $sx, $sy); //Saving the merged image into the destination folder imagejpeg($img, $destination.'/'.$image,100); //Destroying the main image object imagedestroy($img); } //Destroying watermark image object imagedestroy($watermark);
DOWNLOAD CODE
Watermark PHP Script
You may be interested in my another tutorial that will explain how to add watermark to images in a folder and it’s all sub folders.