Are there any PHP libraries or functions that can simplify the process of resizing images with correct aspect ratios?

When resizing images, it's important to maintain the correct aspect ratio to prevent distortion. One way to achieve this is by using PHP libraries or functions that can automatically calculate the correct dimensions based on the original aspect ratio. This can simplify the process and ensure that the resized images look proportional.

function resizeImage($sourceImage, $targetWidth, $targetHeight) {
    list($sourceWidth, $sourceHeight) = getimagesize($sourceImage);
    
    $sourceRatio = $sourceWidth / $sourceHeight;
    $targetRatio = $targetWidth / $targetHeight;
    
    if ($sourceRatio > $targetRatio) {
        $newWidth = $targetWidth;
        $newHeight = $targetWidth / $sourceRatio;
    } else {
        $newWidth = $targetHeight * $sourceRatio;
        $newHeight = $targetHeight;
    }
    
    // Resize the image using the calculated dimensions
    // Code for resizing the image goes here
}