What are some potential pitfalls when using PHP to add borders to PNG images, especially when dealing with transparency?

When adding borders to PNG images with transparency using PHP, a potential pitfall is that the transparency may not be preserved correctly, resulting in a border that covers the entire image. To solve this issue, you can use the imagecopyresampled function to create a new image with the border, while preserving the transparency of the original image.

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

// Get the dimensions of the original image
$width = imagesx($image);
$height = imagesy($image);

// Create a new image with the border
$newImage = imagecreatetruecolor($width + 10, $height + 10);

// Fill the new image with a transparent background
$transparent = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
imagefill($newImage, 0, 0, $transparent);
imagesavealpha($newImage, true);

// Copy the original image onto the new image with the border
imagecopyresampled($newImage, $image, 5, 5, 0, 0, $width, $height, $width, $height);

// Output the new image with the border
imagepng($newImage, 'image_with_border.png');

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