Are there any best practices or guidelines 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 common approach is to calculate the new dimensions based on the desired width or height while preserving the original aspect ratio.

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

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

    $image = imagecreatetruecolor($newWidth, $newHeight);
    $source = imagecreatefromjpeg($imagePath);

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

    imagejpeg($image, $imagePath, 100);

    imagedestroy($image);
    imagedestroy($source);
}

// Usage
$imagePath = 'path/to/image.jpg';
$newWidth = 300;
$newHeight = 200;

resizeImage($imagePath, $newWidth, $newHeight);