What are the best practices for handling image resizing and output in PHP to ensure proper display on web pages?

When handling image resizing in PHP for proper display on web pages, it's important to maintain the aspect ratio of the image to avoid distortion. One common approach is to use the GD library in PHP to resize images while preserving their aspect ratio. Additionally, it's recommended to save the resized image in a web-friendly format such as JPEG or PNG to ensure faster loading times on web pages.

// Function to resize and save image with aspect ratio preservation
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight) {
    list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceImage);
    $sourceAspectRatio = $sourceWidth / $sourceHeight;
    
    $targetAspectRatio = $maxWidth / $maxHeight;
    
    if ($sourceAspectRatio > $targetAspectRatio) {
        $newWidth = $maxWidth;
        $newHeight = $maxWidth / $sourceAspectRatio;
    } else {
        $newWidth = $maxHeight * $sourceAspectRatio;
        $newHeight = $maxHeight;
    }
    
    $sourceImage = imagecreatefromjpeg($sourceImage);
    $targetImage = imagecreatetruecolor($newWidth, $newHeight);
    
    imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
    
    imagejpeg($targetImage, $targetImage, 80);
    
    imagedestroy($sourceImage);
    imagedestroy($targetImage);
}