What are best practices for handling header information in PHP scripts that generate images?

When generating images in PHP scripts, it is important to set the appropriate header information to ensure the image is displayed correctly in the browser. This includes setting the Content-Type header to specify the image type (e.g., image/png, image/jpeg) and using the header() function before any output is sent to the browser.

<?php
// Set the Content-Type header to specify the image type
header('Content-Type: image/png');

// Generate the image (example code)
$image = imagecreate(200, 200);
$bg_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 50, 50, 'Hello World', $text_color);

// Output the image to the browser
imagepng($image);
imagedestroy($image);
?>