What are the best practices for adding a watermark to an image using PHP?

Adding a watermark to an image using PHP involves overlaying a transparent image or text onto the original image to protect it from unauthorized use or to promote branding. This can be achieved by using the GD library in PHP to manipulate images and apply the watermark.

<?php
// Load the original image
$originalImage = imagecreatefromjpeg('original.jpg');

// Load the watermark image
$watermark = imagecreatefrompng('watermark.png');

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

// Calculate the position to place the watermark
$positionX = $originalWidth - $watermarkWidth - 10; // 10px from the right
$positionY = $originalHeight - $watermarkHeight - 10; // 10px from the bottom

// Apply the watermark to the original image
imagecopy($originalImage, $watermark, $positionX, $positionY, 0, 0, $watermarkWidth, $watermarkHeight);

// Output the watermarked image
header('Content-type: image/jpeg');
imagejpeg($originalImage);

// Clean up
imagedestroy($originalImage);
imagedestroy($watermark);
?>