In PHP, what are some recommended methods for handling image scaling and responsiveness within a webpage?

When displaying images on a webpage, it's important to handle image scaling and responsiveness to ensure that they look good on different screen sizes. One recommended method is to use the PHP GD library to resize images dynamically based on the viewport size.

// Get the image file path
$imagePath = 'path/to/image.jpg';

// Get the image size
list($width, $height) = getimagesize($imagePath);

// Calculate the new width based on the desired maximum width
$maxWidth = 500;
$newWidth = $width > $maxWidth ? $maxWidth : $width;

// Calculate the new height proportionally
$newHeight = $height * ($newWidth / $width);

// Create a new image with the calculated dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
$source = imagecreatefromjpeg($imagePath);
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Output the resized image
header('Content-Type: image/jpeg');
imagejpeg($newImage);

// Clean up
imagedestroy($newImage);
imagedestroy($source);