What are the best practices for handling image creation and display in PHP to optimize performance?

When handling image creation and display in PHP, it is important to optimize performance by using caching techniques, resizing images appropriately, and utilizing lazy loading. By implementing these best practices, you can improve the loading speed of your website and enhance the overall user experience.

// Example of resizing and displaying an image with caching in PHP

// Check if the cached image exists
$cached_image_path = 'cached_image.jpg';
if (!file_exists($cached_image_path)) {
    // Load the original image
    $original_image_path = 'original_image.jpg';
    $original_image = imagecreatefromjpeg($original_image_path);

    // Resize the image
    $resized_image = imagescale($original_image, 200, 200);

    // Save the resized image to cache
    imagejpeg($resized_image, $cached_image_path);

    // Free up memory
    imagedestroy($original_image);
    imagedestroy($resized_image);
}

// Display the cached image
echo '<img src="' . $cached_image_path . '" alt="Cached Image">';