What are some best practices for efficiently handling and displaying image sizes in PHP applications?

When handling and displaying images in PHP applications, it's important to efficiently resize and optimize images to improve performance and user experience. One common approach is to use a library like GD or Imagick to resize images to the desired dimensions before displaying them on the website. Additionally, caching resized images can help reduce server load and improve loading times for subsequent requests.

// Example code snippet using GD library to resize and display an image
$sourceImagePath = 'path/to/source/image.jpg';
$targetWidth = 300;
$targetHeight = 200;

list($sourceWidth, $sourceHeight) = getimagesize($sourceImagePath);
$sourceImage = imagecreatefromjpeg($sourceImagePath);
$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);

header('Content-Type: image/jpeg');
imagejpeg($targetImage);
imagedestroy($sourceImage);
imagedestroy($targetImage);