What are some best practices for handling image resizing in PHP?

When resizing images in PHP, it is important to maintain the aspect ratio to prevent distortion. One common approach is to calculate the new dimensions based on a desired width or height while preserving the original aspect ratio.

// Function to resize an image while maintaining aspect ratio
function resizeImage($sourceImage, $newWidth, $newHeight) {
    list($width, $height) = getimagesize($sourceImage);
    $aspectRatio = $width / $height;

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

    $imageResized = imagecreatetruecolor($newWidth, $newHeight);
    $image = imagecreatefromjpeg($sourceImage);
    imagecopyresampled($imageResized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    return $imageResized;
}