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):

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

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

    $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>';

Edited by broj1

6 Years
Discussion Span
Last Post by broj1

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.

Votes + Comments
Pointed me to information that clarified few things about how images work in php.

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.