ChartDirector 6.0 (Perl Edition)

The First CGI Project


The following is exactly the same as The First Project in the previous section, except that instead of creating the chart image in a file, it "streams" the chart image directly to the browser.

This script is intended to be run as a CGI in a web server.

[CGI Version] perldemo_cgi\simplebar.pl
#!/usr/bin/perl

# In the sample code, the ChartDirector for Perl module is assumed to be in "../lib"
use File::Basename;
use lib (dirname($0)."/../lib") =~ /(.*)/;

use perlchartdir;

# The data for the bar chart
my $data = [85, 156, 179.5, 211, 123];

# The labels for the bar chart
my $labels = ["Mon", "Tue", "Wed", "Thu", "Fri"];

# Create a XYChart object of size 250 x 250 pixels
my $c = new XYChart(250, 250);

# Set the plotarea at (30, 20) and of size 200 x 200 pixels
$c->setPlotArea(30, 20, 200, 200);

# Add a bar chart layer using the given data
$c->addBarLayer($data);

# Set the labels on the x axis.
$c->xAxis()->setLabels($labels);

# Output the chart
binmode(STDOUT);
print "Content-type: image/png\n\n";
print $c->makeChart2($perlchartdir::PNG);

The code is almost identical to the code in The First Project, so the details will not be further explained. The major difference is that instead of using BaseChart.makeChart to output the chart as a PNG file, it outputs the chart as a binary string using BaseChart.makeChart2 and streams the data directly to the browser.

The chart image is streamed to the browser using the following code:

#output the chart in PNG format
binmode(STDOUT);
print "Content-type: image/png\n\n";
print $c->makeChart2($perlchartdir::PNG);

The above code first sets STDOUT to binary mode using the Perl "binmode" statement. This is necessary on Windows as Windows handles text mode and binary mode outputs differently. The binmode command has no effect on Linux/FreeBSD/Solaris.

The "print" statement prints the MIME Content-type header, and then a binary string containing the image itself to STDOUT for delivery to the browser.