What is the best practice for resizing images in PHP without distortion?

When resizing images in PHP, it's important to maintain the aspect ratio to prevent distortion. One common approach is to calculate the proportional height or width based on the desired dimensions while preserving the original aspect ratio. This can be achieved by determining the aspect ratio of the original image and then resizing it accordingly.

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

// Get the original dimensions
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);

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

// Calculate the proportional height or width based on the aspect ratio
$ratio = $original_width / $original_height;
if ($desired_width / $desired_height > $ratio) {
    $new_width = $desired_height * $ratio;
    $new_height = $desired_height;
} else {
    $new_width = $desired_width;
    $new_height = $desired_width / $ratio;
}

// Create a new image with the calculated dimensions
$resized_image = imagecreatetruecolor($new_width, $new_height);

// Resize the original image to the new dimensions
imagecopyresampled($resized_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $original_width, $original_height);

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

// Free up memory
imagedestroy($original_image);
imagedestroy($resized_image);