What are some best practices for optimizing PHP code that adds borders to PNG images, especially for larger images?

When adding borders to PNG images in PHP, especially for larger images, it's important to optimize the code to ensure efficient processing and minimal impact on performance. One way to do this is by using the GD library functions in PHP, which provide built-in support for image manipulation. By utilizing functions like imagecopyresampled() instead of imagecopyresized() for resizing images, and ensuring proper memory management, we can improve the efficiency of adding borders to PNG images.

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

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

// Create a new image with a border
$borderSize = 10;
$newWidth = $originalWidth + 2 * $borderSize;
$newHeight = $originalHeight + 2 * $borderSize;
$newImage = imagecreatetruecolor($newWidth, $newHeight);

// Fill the new image with white color for border
$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $white);

// Copy the original image onto the new image with border
imagecopy($newImage, $originalImage, $borderSize, $borderSize, 0, 0, $originalWidth, $originalHeight);

// Output the final image with border
header('Content-Type: image/png');
imagepng($newImage);

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