php header, content type png doesn't work

7.6k views Asked by At

I am having hard time with php headers, i'm trying to create any kind of image in my browser without saving it in a file, but no matter what i do i can't get it working.

So for example if i use this basic example from php manual:

$im = imagecreate(100, 100);

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

imagepng($im);
imagedestroy($im);

It would set correct header and even output that icon which u get when image is not found.

Also i use xampp which have GD enabled, here is my phpinfo GD part:

GD Support  enabled
GD Version  bundled (2.0.34 compatible)
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.4.3
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version 6b
PNG Support enabled
libPNG Version  1.2.46
WBMP Support    enabled
XBM Support enabled

Is my code is wrong or do i need to configure something?

2

There are 2 answers

3
Juicy Scripter On BEST ANSWER

You should not only create the image but also fill it some way:

error_reporting(E_ALL);
ini_set('display_errors', 1);

$im = imagecreate(100, 100) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);

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

imagepng($im);
imagedestroy($im);
0
Another Code On

PHP is probably outputting an error message, thus messing up the binary image data. For this reason I always disable display_errors and enable log_errors in the PHP configuration when working with image scripts; that way you can see any errors without screwing up the output. If you're sure there are no PHP errors in play, try dumping the full script output to a file (ob_start(); at the beginning of the script, file_put_contents("outfile", ob_get_clean()); at the end) and analyze that with a hex editor to see what's messing up the PNG.