Are there best practices for optimizing image loading in PHP?

To optimize image loading in PHP, it is recommended to resize and compress images before serving them to reduce load times and bandwidth usage. One way to achieve this is by using the PHP GD library to resize and compress images on the server side before sending them to the client.

// Load the image
$image = imagecreatefromjpeg('image.jpg');

// Get the image dimensions
$width = imagesx($image);
$height = imagesy($image);

// Calculate the new dimensions for resizing
$newWidth = 300;
$newHeight = ($height / $width) * $newWidth;

// Create a new image with the new dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);

// Resize the image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

// Compress and output the image
imagejpeg($newImage, null, 80);

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