Are there best practices for handling image resizing and maintaining proportions in PHP?

When resizing images in PHP, it's important to maintain the original proportions to avoid distortion. One common approach is to calculate the new dimensions while preserving the aspect ratio of the image.

function resizeImage($sourceImage, $newWidth, $newHeight) {
    list($width, $height) = getimagesize($sourceImage);
    $ratio = $width / $height;

    if ($newWidth / $newHeight > $ratio) {
        $newWidth = $newHeight * $ratio;
    } else {
        $newHeight = $newWidth / $ratio;
    }

    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    $source = imagecreatefromjpeg($sourceImage);

    imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    return $newImage;
}