How can PHP be used to resize images while maintaining proportions?

When resizing images in PHP, it is important to maintain the original aspect ratio to prevent distortion. One way to achieve this is by calculating the new dimensions based on the desired width or height while keeping the proportions intact.

// Set the desired width and height
$desired_width = 300;
$desired_height = 200;

// Get the original image dimensions
list($width, $height) = getimagesize('original_image.jpg');

// Calculate the new dimensions while maintaining aspect ratio
if ($width > $height) {
    $new_width = $desired_width;
    $new_height = $height * ($desired_width / $width);
} else {
    $new_height = $desired_height;
    $new_width = $width * ($desired_height / $height);
}

// Resize the image
$new_image = imagecreatetruecolor($new_width, $new_height);
$original_image = imagecreatefromjpeg('original_image.jpg');
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Save or output the resized image
imagejpeg($new_image, 'resized_image.jpg');