How can the aspect ratio of an uploaded image be maintained when scaling it to fit a specific container size in PHP?

When scaling an image to fit a specific container size in PHP, it is important to maintain the aspect ratio to prevent distortion. This can be achieved by calculating the aspect ratio of the original image and then scaling the image based on the larger dimension of the container size while maintaining the aspect ratio.

// Define the container size
$containerWidth = 400;
$containerHeight = 300;

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

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

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

// Calculate the new dimensions based on the larger dimension of the container size
if ($containerWidth / $containerHeight > $aspectRatio) {
    $newWidth = $containerHeight * $aspectRatio;
    $newHeight = $containerHeight;
} else {
    $newWidth = $containerWidth;
    $newHeight = $containerWidth / $aspectRatio;
}

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

// Scale and copy the original image to the new image
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

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

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