What are the advantages and disadvantages of manually calculating and setting max-width and max-height values for images in PHP compared to using CSS media queries?

When manually calculating and setting max-width and max-height values for images in PHP, the advantage is that you have more control over the image sizes based on specific requirements. However, the disadvantage is that it can be more time-consuming and less flexible compared to using CSS media queries, which allow for responsive design based on screen size.

<?php
// Manually calculate and set max-width and max-height values for images in PHP
$maxWidth = 500;
$maxHeight = 300;

$imagePath = 'path/to/image.jpg';
list($width, $height) = getimagesize($imagePath);

if ($width > $maxWidth || $height > $maxHeight) {
    $ratio = $width / $height;
    
    if ($width > $maxWidth) {
        $newWidth = $maxWidth;
        $newHeight = $newWidth / $ratio;
    }
    
    if ($newHeight > $maxHeight) {
        $newHeight = $maxHeight;
        $newWidth = $newHeight * $ratio;
    }
    
    echo "<img src='{$imagePath}' width='{$newWidth}' height='{$newHeight}' />";
} else {
    echo "<img src='{$imagePath}' width='{$width}' height='{$height}' />";
}
?>