What are the best practices for handling image resizing and output in PHP?

When handling image resizing and output in PHP, it is important to maintain the image quality while resizing and ensure that the output format is appropriate for the intended use. One common approach is to use the GD library in PHP, which provides functions for image manipulation. It is also important to consider the file size of the output image to optimize loading times.

// Example code for resizing and outputting an image using GD library
$sourceImage = 'source.jpg';
$destinationImage = 'resized.jpg';
$desiredWidth = 300;

list($sourceWidth, $sourceHeight) = getimagesize($sourceImage);
$aspectRatio = $sourceWidth / $sourceHeight;
$desiredHeight = $desiredWidth / $aspectRatio;

$source = imagecreatefromjpeg($sourceImage);
$destination = imagecreatetruecolor($desiredWidth, $desiredHeight);

imagecopyresampled($destination, $source, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $sourceWidth, $sourceHeight);

imagejpeg($destination, $destinationImage, 90); // 90 is the quality of the output image
imagedestroy($source);
imagedestroy($destination);