How to Add Watermark in Image using PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hi Dev,

In this tutorial, you will learn how to add watermark in image using php. I would like to show you php watermark image transparent png. if you want to see example of php add watermark to image and save then you are a right place. We will use how to add watermark image in php.

In this tutorial, i will give you two examples of how to add a watermark in images using php. The first example we will take png image and add as watermark. The second example we will use jpg image and add as a watermark. we will use imagecreatefrompng(), imagesx(), imagesy(), getimagesize(), imagecopy(), imagepng(), imagedestroy(), imagecreatefromjpeg() and imagejpeg() functions for adding image to watermark.

So, let's see both examples.

Example 1: Using PNG Image

In First example, we will use png image and add watermark on it. You can download dummy images that i used.

Download demo.png

Download watermark_image.png

Let's copy below code and create index.php file.

index.php

<?php

header('content-type: image/png');

$sourceImage = 'demo.png';

$myWatermark = imagecreatefrompng('watermark_image.png');

$watermarkWidth = imagesx($myWatermark);

$watermarkHeight = imagesy($myWatermark);

$image = imagecreatefrompng($sourceImage);

$imageSize = getimagesize($sourceImage);

$wmX = $imageSize[0] - $watermarkWidth - 20;

$wmY = $imageSize[1] - $watermarkHeight - 20;

imagecopy($image, $myWatermark, $wmX, $wmY, 0, 0, $watermarkWidth, $watermarkHeight);

/*

-------- If you want to save image -------

imagepng($image, 'watermark_image_save.png');

*/

imagepng($image);

imagedestroy($image);

imagedestroy($myWatermark);

Output:

Example 2: Using JPG Image

In First example, we will use jpg image and add watermark on it. You can download dummy images that i used.

Download demo2.jpg

Download watermark_image2.jpg

Let's copy below code and create index.php file.

index.php

<?php

header('content-type: image/jpeg');

$sourceImage = 'demo2.jpg';

$myWatermark = imagecreatefromjpeg('watermark_image2.jpg');

$watermarkWidth = imagesx($myWatermark);

$watermarkHeight = imagesy($myWatermark);

$image = imagecreatefromjpeg($sourceImage);

$imageSize = getimagesize($sourceImage);

$wmX = $imageSize[0] - $watermarkWidth - 20;

$wmY = $imageSize[1] - $watermarkHeight - 20;

imagecopy($image, $myWatermark, $wmX, $wmY, 0, 0, $watermarkWidth, $watermarkHeight);

/*

-------- If you want to save image -------

imagejpeg($image, 'watermark_image_save.jpg');

*/

imagejpeg($image);

imagedestroy($image);

imagedestroy($myWatermark);

Output:

I hope it can help you...

Tags :
Shares