What are best practices for resizing images in PHP for web display?

When resizing images in PHP for web display, it is important to maintain image quality and aspect ratio to ensure optimal performance and appearance on the website. One common approach is to use the GD library in PHP to resize images while preserving their quality.

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

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

// Set the desired width for the resized image
$desiredWidth = 500;

// Calculate the proportional height based on the desired width
$desiredHeight = floor($originalHeight * ($desiredWidth / $originalWidth));

// Create a new image with the desired dimensions
$resizedImage = imagecreatetruecolor($desiredWidth, $desiredHeight);

// Resize the original image to the new dimensions
imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $originalWidth, $originalHeight);

// Output the resized image to the browser or save it to a file
header('Content-Type: image/jpeg');
imagejpeg($resizedImage);

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