Get started with 33% off your first certification using code: 33OFFNEW

Watermark an image dynamically in PHP

2 min read
Published on 5th July 2023

Step 1: Fetch the Online Image

The first step is to fetch the image from the online URL. We use the file_get_contents() function in PHP to read the online file into a string.

In this example we're going to use our default OpenGraph image as the image we're going to watermark, which looks like this:

Accreditly OpenGraph

$imageUrl = 'https://accreditly.io/img/og.png';
$imageContent = file_get_contents($imageUrl);

Step 2: Create an Image Resource

We use the imagecreatefromstring() function to create an image resource from the string obtained from the previous step.

$sourceImage = imagecreatefromstring($imageContent);

Step 3: Load the Watermark Image

Next, we load the watermark image from a local file. For simplicity, let's assume that we have a PNG watermark image named 'watermark.png' in the same directory.

The image we're going to use as a watermark is the winking tongue emoji below:

Winking tongue emoji

$watermarkImage = imagecreatefrompng('watermark.png');

You'll need to adjust the function used here if you're using a jpg or other file type.

Step 4: Get the Dimensions

We need to get the width and height of both the source image and the watermark image.

$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);

$watermarkWidth = imagesx($watermarkImage);
$watermarkHeight = imagesy($watermarkImage);

Step 5: Position the Watermark

We need to decide where to place the watermark on the source image. In this example, we will place it at the bottom right corner.

$destX = $sourceWidth - $watermarkWidth - 10;  // 10px padding from right
$destY = $sourceHeight - $watermarkHeight - 10;  // 10px padding from bottom

Step 6: Merge the Watermark with the Source Image

We use the imagecopy() function to merge the watermark image with the source image.

imagecopy($sourceImage, $watermarkImage, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight);

Step 7: Output the Watermarked Image

Now, we can output the resulting watermarked image to the browser. Before we do this, we need to set the correct content type header.

header('Content-type: image/png');
imagepng($sourceImage);

Step 8: Cleanup

Finally, we should clean up the image resources that we have created.

imagedestroy($sourceImage);
imagedestroy($watermarkImage);

That's it! Now you can dynamically add a watermark to any image on your PHP website.

You should be left with an image that looks like the following:

Accreditly Watermark Example

Please note, fetching images with file_get_contents() might not work if 'allow_url_fopen' is disabled in your PHP configuration, and not all images on the internet can be accessed due to CORS policies.