Re: Using GD on the fly to add a graph to a web page

[email protected] (Sean Davis) Tue, 3 Feb 2009 07:46:14 -0500
Newsgroups perl.beginners.cgi
Message-ID <[email protected]>
On Mon, Feb 2, 2009 at 8:26 AM, bacoms <[email protected]> wrote:

> I've got a web page that includes a graph. I achieve this with code
> that looks like:
>
>     print "Content-type: text/html\n\n";
>                          etc
>                          etc
>      my($myImage) = $myChart->plot(\@data) or die $myChart->error;
>
>      open(IMAGE, ">Images/zzzgraph.png") or die $!;
>      binmode IMAGE;
>      print IMAGE $myImage->png;
>      close IMAGE;
>
>      print "    <img src='Images/zzzgraph.png' width='800'
> height='600'>\n";
>
> Is it possible to eliminate the need to first write the image to
> disk?
>
> All my attempts at trying this have all failed. The best I get is with
> the following code:
>
>     print "Content-type: text/html\n\n";
>                          etc
>                          etc
>      my($myImage) = $myChart->plot(\@data) or die $myChart->error;
>      print $myImage->png;
>
> which produces gibberish where the chart should be. (cribbed from
> http://linuxgazette.net/issue83/padala.html )
>
> I suspect is that this specifies "Content-type: image/png\n\n" whereas
> my web page specifies "Content-type: text/html\n\n".
>
> I've tried specifying both content-types on my web page but this
> results on the user being asked if they want to save the script
> (??????).
>
> Can it be done and how????
>

The issue is that you cannot return the image embedded in the HTML.  You can
write a CGI script that returns an image (only), though.  You are correct
that this would use the png content type.  Therefore, to construct a page
that contains an image within HTML, your page would return HTML that
includes an img tag that has your CGI for image production as the source.

Sean