What are the best practices for optimizing PHP code to output images in different formats like JPEG or PNG?

To optimize PHP code for outputting images in different formats like JPEG or PNG, you can use the GD library functions to manipulate and save images in the desired format. Make sure to properly handle errors and clean up resources after processing the images.

// Example code snippet for optimizing PHP code to output images in different formats

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

// Create a new image in the desired format (PNG in this case)
$output_image = 'output.png';
imagepng($image, $output_image);

// Output the image to the browser
header('Content-Type: image/png');
readfile($output_image);

// Clean up resources
imagedestroy($image);