What are some best practices for efficiently displaying images in PHP to avoid overloading memory and wasting time?

When displaying images in PHP, it's important to avoid overloading memory and wasting time by resizing images before outputting them. One way to achieve this is by using the PHP GD library to resize images on the fly and output them directly to the browser without saving multiple versions of the same image on the server.

<?php
// Path to the image file
$imagePath = 'path/to/image.jpg';

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

// Set the desired width for the resized image
$desiredWidth = 300;

// Calculate the new height based on the desired width
$desiredHeight = floor($height * ($desiredWidth / $width));

// Create a new image resource
$newImage = imagecreatetruecolor($desiredWidth, $desiredHeight);

// Load the original image
$originalImage = imagecreatefromjpeg($imagePath);

// Resize the original image to the new dimensions
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $width, $height);

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

// Free up memory
imagedestroy($newImage);
imagedestroy($originalImage);
?>