What is the recommended approach for resizing images in PHP to maintain aspect ratio?

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

function resize_image($image_path, $new_width, $new_height) {
    list($width, $height) = getimagesize($image_path);
    $aspect_ratio = $width / $height;
    
    if ($new_width / $new_height > $aspect_ratio) {
        $new_width = $new_height * $aspect_ratio;
    } else {
        $new_height = $new_width / $aspect_ratio;
    }
    
    $image = imagecreatetruecolor($new_width, $new_height);
    $source = imagecreatefromjpeg($image_path);
    
    imagecopyresampled($image, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
    imagejpeg($image, 'resized_image.jpg', 100);
    imagedestroy($image);
}