How can PHP scripts be optimized to automatically scale images to fit within a specified div size without distortion?

To automatically scale images to fit within a specified div size without distortion in PHP, you can use the GD library functions to resize the image while preserving its aspect ratio. First, calculate the aspect ratio of the image and the div size, then resize the image accordingly.

// Specify the maximum width and height of the div
$divWidth = 300;
$divHeight = 200;

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

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

// Calculate the aspect ratio of the image
$aspectRatio = $originalWidth / $originalHeight;

// Calculate the aspect ratio of the div
$divAspectRatio = $divWidth / $divHeight;

// Resize the image based on the aspect ratio
if ($aspectRatio > $divAspectRatio) {
    $newWidth = $divWidth;
    $newHeight = $divWidth / $aspectRatio;
} else {
    $newHeight = $divHeight;
    $newWidth = $divHeight * $aspectRatio;
}

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

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

// Clean up
imagedestroy($image);
imagedestroy($resizedImage);