简体   繁体   中英

header('Content-type: image/png'); makes the browser all black

This a script from PHP.net

// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));    
// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));
// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);
// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);
// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

The line HEADER make the browser all black! Why? Whats wrong?

header('Content-type: image/png');

Forces your browser to interpret your output as an image of type png.

Even though your code is fine and does not produce an error. It's very likely that you are missing GD or your environment is badly configured and do return an error. But because of the header , the error output is behing interpreted as an image.

Try removing it and ensure that the displayed string is a correct raw png data.

Edit: After debugging with OP, it came out that his script had a whitespace character before declaring open php tags <?php . This small thing was sent as well with the correct png data and messed up the whole data for the browser interpreting it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM