Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Heres my code, I run it using localhost/script.cgi from my browser -
#!C:/Perl/bin/perl -w use strict; use CGI::Carp qw(fatalsToBrowser); use GD; #createanewimage my $im=new GD::Image(100,100); #allocatesomecolors my $white=$im->colorAllocate(255,255,255); my $black=$im->colorAllocate(0,0,0); my $red=$im->colorAllocate(255,0,0); my $blue=$im->colorAllocate(0,0,255); #makethebackgroundtransparentandinterlaced $im->transparent($white); $im->interlaced('true'); #Putablackframearoundthepicture $im->rectangle(0,0,99,99,$black); #Drawablueoval $im->arc(50,50,95,75,0,360,$blue); #Andfillitwithred $im->fill(50,50,$red); #makesurewearewritingtoabinarystream binmode STDOUT; #ConverttheimagetoPNGandprintitonstandardoutput print $im->png;
When I try to run this from my browser, I get an Internal server error, and in my error log I get -
[Sat Mar 15 20:58:45 2003] [error] [client 127.0.0.1] malformed header + from script. Bad header=‰PNG: script.cgi
I can open gen.png fine from the browser using localhost/gen.png. I'm running on Win XP, and I have Apache installed. Maybe Apache is the problem? The script works fine on the command line. ANy ideas?

Replies are listed 'Best First'.
Re: Error displaying PNGs
by pfaut (Priest) on Mar 15, 2003 at 21:11 UTC

    You need to output HTTP headers indicating a proper Content-Type for a PNG image. Before the binmode, you want something like

    print "Content-type: image/x-png\n\n";
    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
      The right MIME type is image/png though. All else will result in undefined behaviour, even if some browsers will work.

      Makeshifts last the longest.

        Thanks, Aristotle. I've long since lost my pointer to a list of valid content types. I posted what I last remembered seeing which was likely a long time ago before PNG files were popular.

        --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';