Jesus Loves GRASS

Technical blog about GRASS/GIS,open source geoinformatics and MAPSERVER.

Wednesday, February 27, 2008

The image .... cannot be displayed, because it contains errors.

"The image 'http://localhost/ACI/test.php' cannot be displayed, because it contains errors." Was the only thing I was getting when running some examples and source codes for image creation using GD and PHP. I googled it and all the information found concerned bad installation of GD and other libraries.

But when dumping the GD info with var_dump(gd_info()); everything was ok.

In the end I discovered that actually the error is not related to GD but with the header used to send the image, this example works fine:

<?php
header("Content-type: image/png");
$im = imagecreate(210, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 25, 25, 25);
imageline($im,10,10,20,20,$text_color);
imagepng($im);
imagedestroy($im);
?>

But something like this:
<?php
//Something, source or text
?>
<?php
header("Content-type: image/png");
$im = imagecreate(210, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 25, 25, 25);
imageline($im,10,10,20,20,$text_color);
imagepng($im);
imagedestroy($im);
?>

Will only generate the stupid GD error message.

The header() needs to be the first thing in the PHP code as explained in the PHP doc "Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file."

Labels: , , , ,

3 Comments:

At 14/3/08 9:33 AM, Anonymous Anonymous said...

You can also use buffering with ob_start() and ob_end_flush().

 
At 29/4/10 9:07 AM, Anonymous Anonymous said...

After hitting my head to my notebook for about 1 hour, I finally founded this blog.
Really appreciated!

 
At 27/2/15 8:26 AM, Anonymous Anonymous said...

Thanks. That was the exact problem. When I remove my tag of require_once('db_connection.php') and inserted the db connections manually the error got corrected.

 

Post a Comment

<< Home