Watermark Images in PHP And Save File on Server

gdlogobigI have read plenty of tutorials on the internet about watermarking images on the internet. All of them are decent, but all of them output the images on the browser using the header option of the PHP. But, what I wanted to do was watermark and existing or uploaded image on the server and save the file.

Here, is the function i have created after modifying the default code provided by PHP.net. Just make use of this function in your code.
{code type=php}function watermark_image($input_name, $extn ) {
$stamp = imagecreatefrompng(‘theme/stamp.png’); //Input the location of your Watermark Here.

if ($extn == “png”)
$im = imagecreatefrompng($input_name);
if ($extn == “jpg” || $extn == “jpeg”)
$im = imagecreatefromjpeg($input_name);
if ($extn == “gif”)
$im = imagecreatefromgif($input_name);

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 1;
$marge_bottom = 5;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) – $sx – $marge_right, imagesy($im) – $sy – $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory

imagejpeg($im,$input_name); //This part overwrites the image.
imagedestroy($im);
}
{/code}
Most of the code above is self-explanatory. Still, if you need any help in understanding it just comment below and I will try to help.

All You need to Supply to the function is the Path to the image, and the extension of the image which you will understand after seeing the complete code.

This Program Takes the Watermark which is stored somewhere on the server, and places it on the image provided to the function. Also, in the end it saves the watermarked image as the same name as the input image. You can also change it by modifying the 3rd last line.

If you want to pass the watermark in the function as well, you can do it. But, you need to then edit the first line of the code and replace ‘theme/stamp.png’ with the value u passed in the function.

This Program makes use of the GD library which is by default enabled in almost all the PHP installations. But, just in case if you are on a old server or hosting, you might want to check if GD is enabled or not. You can do that by searching for GD in your phpinfo file.

Leave a Reply

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