Search code examples
phpimagewatermark

How to add watermark to an image at the bottom right in PHP?


I am trying to add watermark to an image in PHP. I am using the below code that works fine. But I am facing challenges in the following ways.

<?php

 function watermark_image($target, $wtrmrk_file, $newcopy) {
    $watermark = imagecreatefrompng($wtrmrk_file);
    imagealphablending($watermark, false);
    imagesavealpha($watermark, true);
    $img = imagecreatefromjpeg($target);
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    $wtrmrk_w = imagesx($watermark);
    $wtrmrk_h = imagesy($watermark);
    imagecopy($img, $watermark, 500, 200, 0, 0, 100, 100);
    imagejpeg($img, $newcopy, 100);
    imagedestroy($img);
    imagedestroy($watermark);
}

watermark_image('1.jpg','assets/images/watermark.png', 'new_image_name.jpg');

exit();
?>

I am trying to achieve a code in which I can apply a watermark to any image on the bottom right side. with a fixed height and width of 150x150. I am trying from past 2 hours but no success in getting it accurately placed.

Does anybody has an idea? how to achieve it? It would be really very helpful.


Solution

  • You are placing the watermark image in the wrong location. It needs to be relative to the width and height of the source image, as well as the dimensions of the watermark image. This solves your problem:

      imagecopy($img, $watermark, $img_w - $wtrmrk_w, $img_h - $wtrmrk_h, 0, 0, $wtrmrk_w, $wtrmrk_h);