Hi all

I would like to display several charts on a webpage. I have designed a class that would draw each chart using GD and based on data set by a public method. Unfortunately instead of charts being drawn I get an error message:

The image ... cannot be displayed because it contains errors

I have googled and checked similar threads here on DW but nothing helped. I think I do not have any output sent before headers (checked with if(headers_sent())) which is usually the cause for this error. Maybe my class is coded incorrectly. The same code works fine if put in an ordinary php file, but I would prefer to have a class for this purpose. If anybody coud have a look at the code and give me a hint I would really appreciate it.

The Chart class (simplified, but does not work):

<?php
class Chart
{
    // data for drawing the chart
    protected $chart_data = array();

    public function __construct() 
    {
    }

    public function set_chart_data($data) 
    {
        $this->chart_data = $data;
    }

    public function draw_chart() 
    {
        header("Content-type: image/png");

        $width = $this->chart_data['width'];
        $height = $this->chart_data['height'];

        // create image
        $image=imagecreatetruecolor($width, $height) 
            or die('Cannot iInitialize new GD image stream');;

        // define colors
        $fill_color=imagecolorallocate($image, 127, 127, 127);

        // draw a filled rectangle
        imagefilledrectangle($image, 0, 0, $width, $height, $fill_color);

        // output image and destroy it
        imagepng($image);
        imagedestroy($image);
    }
}
?>

And the php file to display the chart (simplified):

<?php
    require_once('Chart.php');
    $ch = new Chart;

    // set data for the chart
    $w = 250; $h = 250;
    $ch->set_chart_data( array('width' => $w,'height' => $h));

    echo '<html><head></head><body>';
    echo '<p>Test GD</p>';
    // display the chart
    echo "<p><img src=\"{$ch->draw_chart()}\" width=\"$w\" height=\"$h\" /></p>";
    echo '</body></html>';
?>

Recommended Answers

All 2 Replies

If you want to put raw data in the image tag, you'll have to base64 encode it. You can read about it here. Whether it is a good idea, I don't know. I usually link to a script that outputs the image.

commented: Pointed me to information that clarified few things about how images work in php. +4

Thanks. I guess I'll go back to a script that draws image which worked fine.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.