Are there any best practices for optimizing image loading and display on a PHP website?

One best practice for optimizing image loading and display on a PHP website is to resize and compress images before serving them to users. This can help reduce loading times and improve website performance. Additionally, lazy loading images can be implemented to only load images when they are visible on the screen, further improving loading times.

// Resize and compress image before serving
function resize_image($file, $new_width, $new_height) {
    list($width, $height) = getimagesize($file);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($file);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    imagejpeg($image_p, null, 80); // 80 is the quality percentage
    imagedestroy($image_p);
}

// Lazy load images
echo '<img src="placeholder.jpg" data-src="image.jpg" class="lazyload" />';