Jump to content

Strange issue with custom function and image drawing


patrick89

Recommended Posts

Hi everyone,

 

I'm playing around with PHP at the moment to make a graph (first time really using the image drawing functions in PHP, so it's a bit of an experiment at the moment).

 

All was going well until I tried to use a function within the code. If I try to call a function which isn't one of the PHP image functions, the image doesn't display?

 

For example, including drawTimeLine() stops the image from displaying (simplified version of the code i've been working on but has the same problem...):

<?php
header("Content-type: image/png");

$timelineGraph = ImageCreate(300,300) or die("Cannot Initialize new GD image stream");

// Formatting
$black = ImageColorAllocate($timelineGraph, 0, 0, 0);
$red = ImageColorAllocate($timelineGraph, 255, 0, 0);

function drawTimeline($startWeek, $startDay, $endWeek, $endDay) {
ImageLine($timelineGraph, 0, 0, 299, 299, $red);
}

drawTimeline(1,1,1,1);

ImagePng($timelineGraph);

ImageDestroy($timelineGraph);

?>

 

While if you comment drawTimeline() out, the image will still appear (just as a black background, but still appears on screen).

 

I'm inserting it using the following code which I believe is right?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Timeline Graph</title>
</head>
<body>

<p><img src="test.php" alt="Graph" /></p>

</body>
</html>

 

Can't work out what the problem is? Does PHP not allow for custom functions within image creation?

 

Any help is much appreciated... I can't work out why this isn't working! I was going well up until now!

When working with images if you can't figure out the problem it's usually a good idea to comment out the Content-type header so that you can see the error you're getting. In your case you have a scope problem. Neither $timelineGraph nor $red is set within the scope of that function. You can either make them globals (which is a bad practice), or preferably pass those variable as parameters.

 

Ex:

 

<?php
header("Content-type: image/png");

$timelineGraph = ImageCreate(300,300) or die("Cannot Initialize new GD image stream");

// Formatting
$black = ImageColorAllocate($timelineGraph, 0, 0, 0);
$red = ImageColorAllocate($timelineGraph, 255, 0, 0);

function drawTimeline($im, $color, $startWeek, $startDay, $endWeek, $endDay) {
	ImageLine($im, 0, 0, 299, 299, $color);
}
drawTimeline($timelineGraph, $red, 1,1,1,1);

ImagePng($timelineGraph);

ImageDestroy($timelineGraph);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.