ChartDirector Ver 4.1 (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

# Include current script directory in the module path (needed on Microsoft IIS).
# This allows this script to work by copying ChartDirector to the same directory
# as the script (as an alternative to installation in Perl module directory)
use File::Basename;
use lib dirname($0);

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.

Note that in the above code, the first few lines are:

#Include current script directory in the module path (needed on Microsoft IIS).
#This allows this script to work by copying ChartDirector to the same directory
#as the script (as an alternative to installation in Perl module directory)
use File::Basename;
use lib dirname($0);

The above is to make sure the script can run on Microsoft web servers without installing ChartDirector in the Perl module search path (that is, by just copying ChartDirector to the script directory.) If you are not using Microsoft web servers, or you have install ChartDirector in your Perl module search path, the above code is not necessary.

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.