What are the best practices for resizing PNG images in PHP to ensure that the transparent background is not altered or lost?

When resizing PNG images in PHP, it's important to use functions that preserve the transparent background. One way to achieve this is by using the imagecopyresampled() function instead of imagecopyresized(). This function maintains the alpha channel of the image, ensuring that the transparent background is not altered or lost during the resizing process.

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

// Create a new image with the desired dimensions
$newWidth = 200;
$newHeight = 200;
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);

// Preserve transparency while resizing
imagealphablending($resizedImage, false);
imagesavealpha($resizedImage, true);

// Resize the image while maintaining transparency
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($originalImage), imagesy($originalImage));

// Save the resized PNG image
imagepng($resizedImage, 'resized.png');

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