How can PHP developers ensure that images maintain their original proportions while resizing?

When resizing images in PHP, developers can ensure that the images maintain their original proportions by calculating the aspect ratio of the original image and then using this ratio to resize the image proportionally in both dimensions.

<?php
function resize_image($image_path, $new_width, $new_height) {
    list($width, $height) = getimagesize($image_path);
    $original_aspect = $width / $height;
    $new_aspect = $new_width / $new_height;

    if ($original_aspect >= $new_aspect) {
        $final_width = $new_width;
        $final_height = $new_width / $original_aspect;
    } else {
        $final_width = $new_height * $original_aspect;
        $final_height = $new_height;
    }

    $image = imagecreatetruecolor($final_width, $final_height);
    $original_image = imagecreatefromjpeg($image_path);
    imagecopyresampled($image, $original_image, 0, 0, 0, 0, $final_width, $final_height, $width, $height);

    return $image;
}
?>