I was trying to run an example given in a book that produces a PNG image on the page:

<?php
//set up image
$height = 200;
$width = 200;

$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 0, 0, 255);

//draw on image
imagefill($im, 0, 0, $blue);
imageline($im, 0, 0, $width, $height, $white);
imagestring($im, 4, 50, 150, 'Sales', $white);

//output image
Header('Content-type: image/png');
imagepng($im);

//clean up
imagedestroy($im);
?>

The problem is that when I run it, all I get is a broken image icon. Firefox additionally tells me that the image can't be displayed because it contains error. What am I doing wrong?

有帮助吗?

解决方案

Your content type is wrong. You're making a JPG but telling the browser it is a PNG:

Header('Content-type: image/png');
imagejpeg($im);

should be

Header('Content-type: image/jpeg');
imagejpeg($im);

edit

This question was edited to correct this. This edit solves the problem: http://codepad.viper-7.com/FTW3g0

其他提示

I am able to run this in PHP 5.4.10 without issue. And viewable as a PNG:

enter image description here

What version of PHP are you using? Are you sure the GD library is installed? Open up a PHP file & place this phpinfo command at the top of it to see if GD is loaded:

<?php
  phpinfo();
?>

That said, I did notice an odd error in PHP 5.2.17 which I can switch to in my MAMP setup: Even if I have the command die(); after your code, the page bombs out. Something is different in the PHP parser between PHP 5.4.10 and PHP 5.2.17 it seems. But that is just me. Unclear what your setup is like.

EDIT I think I figured out the issue. Some browsers are case sensitive to headers. So change this:

//output image
Header('Content-type: image/png');
imagepng($im);

To this:

//output image
header('Content-Type: image/png');
imagepng($im);

Note the capital T in Content-Type in my edit. Try that out.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top