image contains errors problems in PHP
The goal was to test out the PHP image functions using GD. The web server is Apache, and the platform is windows. PHP5.0
The later versions of PHP come with GD out of the box, you just need to go into php.ini and make the extension available.
Having done this, I tried out this code.
<?PHP
$im = imageCreate(50,50);
$background = imageColorAllocate($im, 100, 100, 255);
header("Content-type: image/gif");
imagegif($im);
imageDestroy($im);
?>
And I got a message from firefox stating that:
The image http://localhost/gdtest/simpleimage.php cannot be displayed, because it contains errors.
The apache error log showed nothing. The script was executing apparently without error, but the image was broken.
If you modify the code so that the image is written to a file rather than transferred to a browser, it works:
<?PHP
$im = imageCreate(50,50);
$background = imageColorAllocate($im, 100, 100, 255);
//header("Content-type: image/gif");
imagegif($im, 'filename.gif');
imageDestroy($im);
?>
The only changes made were to comment out the header command and to add the filename parameter to the imagegif() function call. Checking in the .php file directory revealed a .gif image with the proper filename that would open in any browser or other image viewer.
So why didn't it work when I tried to send the image straight to a browser? Turns out I had a leading carriage return prior to the <?php tag.
It's important to realize that when you're sending an image directly to the browser, all of the information that goes to the browser is supposed to be image.
If you're new to PHP (like me) you might be accustomed to HTML where an additional Carriage Return here and there doesn't change anything. Not true when you're transmitting an image directly to the browser.
If, prior to your script you have a carriage return, any text, even a single blank space, it will result in a corrupt image file.
You cannot echo or print anything. Your <?php must be at the very top left of the .php file. Just create the image, send it, and destroy it, that's it.
Oddly enough, it seems that adding things after the end of the script (?>) have no effect (meaning the image will work). I presume that imagegif() encodes the size of the image and that the browser just stops reading after that many bytes.
There are many other things that can cause this problem. Check your apache error log for missing functions, etc. Sometimes support for a font is missing, or you're trying to use an image format that you don't have installed support for.
If you have errors in the error.log, this isn't your problem. If you can't write an image to file, this isn't your problem. If, however, Apache gives you no errors, and you can write to file but not to a browser, then it is very likely that you are corrupting the image by outputting unwanted text.
I found a ton of people asking this question in various places, and I hope I've helped a couple of them.

