Can PHP be used to automatically resize images that are too large for the browser without losing quality?

When displaying images on a website, it's important to resize them appropriately to ensure they fit within the browser window without losing quality. PHP can be used to automatically resize images that are too large by using the GD library functions. By calculating the desired dimensions based on the browser window size and then resizing the image accordingly, you can ensure that the image is displayed properly without distortion.

<?php
// Set the maximum width and height for the resized image
$maxWidth = 800;
$maxHeight = 600;

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

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

// Calculate the new dimensions for the resized image
if ($originalWidth > $maxWidth || $originalHeight > $maxHeight) {
    $ratio = min($maxWidth / $originalWidth, $maxHeight / $originalHeight);
    $newWidth = $originalWidth * $ratio;
    $newHeight = $originalHeight * $ratio;
} else {
    $newWidth = $originalWidth;
    $newHeight = $originalHeight;
}

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

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

// Output the resized image
header('Content-Type: image/jpeg');
imagejpeg($resizedImage);

// Clean up
imagedestroy($originalImage);
imagedestroy($resizedImage);
?>