How can PHP developers ensure that images maintain their aspect ratio and do not get distorted during resizing processes?

When resizing images in PHP, developers can ensure that the aspect ratio is maintained and images do not get distorted by calculating the new dimensions based on the original aspect ratio. This can be achieved by determining whether the width or height should be resized proportionally to maintain the aspect ratio.

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

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

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

    return $imageResized;
}