Share this:

In the digital world, protecting your visual content from unauthorized use has become increasingly important. One way to deter unauthorized use is by adding a watermark to your images. In this blog post, we will discuss how to add a watermark to an image using PHP. We will be using the GD library, which is widely supported and offers a range of powerful image manipulation functions.

Getting Started

Before we dive into the code, ensure that you have the GD library installed and enabled in your PHP environment. You can check if the GD library is enabled by creating a PHP file with the following code:

<?php
phpinfo();
?>

If the GD library is not enabled, you will need to enable it in your PHP configuration file (php.ini).

Now that you have the GD library ready, let’s start by adding a watermark to an image using PHP.

Step 1: Load the Image and Watermark

First, we need to load the image and watermark files. In this example, we will be using JPEG images, but you can also use other formats such as PNG or GIF.

<?php
// Load the image and watermark
$imageFile = 'path/to/image.jpg';
$watermarkFile = 'path/to/watermark.png';

$image = imagecreatefromjpeg($imageFile);
$watermark = imagecreatefrompng($watermarkFile);
?>

Step 2: Determine Watermark Position

Next, we need to determine the position of the watermark on the image. In this example, we will place the watermark at the bottom-right corner with a margin of 10 pixels.

<?php
// Get image and watermark dimensions
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
$watermarkWidth = imagesx($watermark);
$watermarkHeight = imagesy($watermark);

// Calculate watermark position
$watermarkPosX = $imageWidth - $watermarkWidth - 10;
$watermarkPosY = $imageHeight - $watermarkHeight - 10;
?>

Step 3: Apply the Watermark

Now that we have the watermark position, we can apply the watermark to the image using the imagecopy function.

<?php
// Apply the watermark
imagecopy($image, $watermark, $watermarkPosX, $watermarkPosY, 0, 0, $watermarkWidth, $watermarkHeight);
?>

Step 4: Output the Watermarked Image

After applying the watermark, we can save the watermarked image to a file or output it directly to the browser.

<?php
// Set the content type
header('Content-Type: image/jpeg');

// Output the watermarked image
imagejpeg($image);

// Free memory
imagedestroy($image);
imagedestroy($watermark);
?>

Conclusion

In this blog post, we have demonstrated how to add a watermark to an image using PHP and the GD library. This method can be easily adapted to work with different image formats and watermark positions. With this simple technique, you can protect your visual content from unauthorized use and ensure that your images always carry your brand’s identity.

Share this:

Categorized in: