PASSWORD RESET

Your destination for complete Tech news

PHP

How to add a watermark on an image in PHP?

517 0
< 1 min read

In PHP, you can add a watermark to an image using the GD library. Here’s an example:

// Load the original image
$filename = 'path/to/image.jpg';
$originalImage = imagecreatefromjpeg($filename);

// Load the watermark image
$watermarkFilename = 'path/to/watermark.png';
$watermarkImage = imagecreatefrompng($watermarkFilename);

// Get the dimensions of the original image and watermark image
$originalWidth = imagesx($originalImage);
$originalHeight = imagesy($originalImage);
$watermarkWidth = imagesx($watermarkImage);
$watermarkHeight = imagesy($watermarkImage);

// Calculate the position of the watermark in the center of the original image
$posX = ($originalWidth / 2) - ($watermarkWidth / 2);
$posY = ($originalHeight / 2) - ($watermarkHeight / 2);

// Add the watermark to the original image
imagecopy($originalImage, $watermarkImage, $posX, $posY, 0, 0, $watermarkWidth, $watermarkHeight);

// Save the modified image
$outputFilename = 'path/to/output.jpg';
imagejpeg($originalImage, $outputFilename);

// Free up memory
imagedestroy($originalImage);
imagedestroy($watermarkImage);

In this example, we load the original image using the imagecreatefromjpeg() function and the watermark image using the imagecreatefrompng() function. We then calculate the position of the watermark in the center of the original image, using the dimensions of the two images. We add the watermark to the original image using the imagecopy() function, and save the modified image using the imagejpeg() function. Finally, we free up memory using the imagedestroy() function.

Note that this example assumes that the original image and watermark image are in JPEG and PNG format, respectively. If your images are in a different format, you may need to use a different function to load them. Additionally, you may want to add additional logic to handle cases where the watermark is larger than the original image or where the watermark should be placed in a different position.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.