What are some common methods for resizing images in PHP while maintaining proportions?

When resizing images in PHP, it is important to maintain the aspect ratio to avoid distorting the image. One common method to achieve this is by calculating the new dimensions while preserving the original proportions. This can be done by determining whether the width or height needs to be adjusted and then resizing the image accordingly.

function resize_image($image_path, $new_width, $new_height) {
    list($width, $height) = getimagesize($image_path);
    $original_image = imagecreatefromjpeg($image_path);
    
    $ratio = $width / $height;
    if ($new_width / $new_height > $ratio) {
        $new_width = $new_height * $ratio;
    } else {
        $new_height = $new_width / $ratio;
    }
    
    $resized_image = imagecreatetruecolor($new_width, $new_height);
    imagecopyresampled($resized_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
    imagejpeg($resized_image, 'resized_image.jpg', 100);
    imagedestroy($original_image);
    imagedestroy($resized_image);
}

resize_image('original_image.jpg', 300, 200);