How can the aspect ratio of an image be calculated and maintained during resizing in PHP?

When resizing an image in PHP, it's important to maintain the aspect ratio to prevent distortion. To calculate the aspect ratio, you can divide the width by the height of the image. To maintain the aspect ratio during resizing, you can calculate the new dimensions based on the desired width or height while keeping the aspect ratio constant.

<?php

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

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

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

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

    imagejpeg($image, $imagePath, 100);
}

// Example usage
resizeImage('image.jpg', 300, 200);

?>