What are some best practices for calculating new dimensions for images in PHP to maintain quality and aspect ratio, according to the solutions provided in the thread?

When resizing images in PHP, it is important to maintain the quality and aspect ratio to prevent distortion. One way to achieve this is by calculating the new dimensions proportionally based on the original dimensions. This can be done by determining the scaling factor for both width and height and then applying it to the new dimensions.

function calculateNewDimensions($originalWidth, $originalHeight, $maxWidth, $maxHeight) {
    $widthRatio = $maxWidth / $originalWidth;
    $heightRatio = $maxHeight / $originalHeight;
    
    if ($widthRatio < $heightRatio) {
        $newWidth = $maxWidth;
        $newHeight = round($originalHeight * $widthRatio);
    } else {
        $newHeight = $maxHeight;
        $newWidth = round($originalWidth * $heightRatio);
    }
    
    return ['width' => $newWidth, 'height' => $newHeight];
}

// Example of how to use the function
$originalWidth = 800;
$originalHeight = 600;
$maxWidth = 400;
$maxHeight = 300;

$newDimensions = calculateNewDimensions($originalWidth, $originalHeight, $maxWidth, $maxHeight);
echo "New Width: " . $newDimensions['width'] . ", New Height: " . $newDimensions['height'];