How can PHP developers optimize memory usage when processing images with watermarks?

When processing images with watermarks in PHP, developers can optimize memory usage by resizing the image before applying the watermark. This reduces the overall size of the image in memory, making it quicker and more efficient to process.

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

// Resize the image to reduce memory usage
$width = imagesx($image);
$height = imagesy($image);
$newWidth = $width / 2; // Resize to half the original width
$newHeight = $height / 2; // Resize to half the original height
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Apply watermark to the resized image
$watermark = imagecreatefrompng('watermark.png');
imagecopy($resizedImage, $watermark, 0, 0, 0, 0, imagesx($watermark), imagesy($watermark));

// Output the final image
imagepng($resizedImage, 'watermarked.png');

// Free up memory
imagedestroy($image);
imagedestroy($resizedImage);
imagedestroy($watermark);