What are the challenges of resizing images to a specific aspect ratio in PHP?

Resizing images to a specific aspect ratio in PHP can be challenging because it involves calculating the new dimensions while maintaining the original aspect ratio. One way to solve this is by determining whether the image needs to be cropped or padded to fit the desired aspect ratio.

function resizeImageToAspectRatio($imagePath, $aspectRatio) {
    list($width, $height) = getimagesize($imagePath);
    
    $originalAspectRatio = $width / $height;
    if ($originalAspectRatio < $aspectRatio) {
        $newWidth = $height * $aspectRatio;
        $newHeight = $height;
    } else {
        $newWidth = $width;
        $newHeight = $width / $aspectRatio;
    }
    
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
    $originalImage = imagecreatefromjpeg($imagePath);
    
    imagecopyresampled($resizedImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    imagejpeg($resizedImage, 'resized_image.jpg');
}