PHP Images

This section demonstrates how to create an empty canvas and put a line graph on it using the GD PHP extension. Starting with PHP 4.3, a version of GD is bundled into PHP by default.

First, create a canvas by either of:

	$image = ImageCreate($width, $height);  - Create a new palette based canvas.
	$image = ImageCreateTrueColor($width, $height); - Create a new true color canvas.

The variable $image is a resource which is used to identify the canvas.

To see this new canvas, use

	header('Content-Type: image/png');
	ImagePNG($image);

The canvas is, by default, black. To change this, obtain a color resource using

	$color = ImageColorAllocate($image, $red, $green, $blue);

where $red, $green, and $blue are values in Hex (0xFF), Decimal (255), etc. If you have a palette based canvas, that function call will change the color. For a true color canvas, call:

	ImageFill($image, $x, $y, $color);

Where $x and $y are the start point coordinates. For a palette based canvas, it is not necessary to call ImageFill because the first call to ImageColorAllocate() sets the background color

Now that the basic canvas graphic has been created, it's time to build the graph. Lines are drawn using ImageLine()

	ImageLine($image, $x1, $y1, $x2, $y2, $color);

where $x1, $y1 are the starting points, and $x2, $y2 are the ending points. $color is a color resource created with ImageColorAllocate()

True Type text can be painted on the canvas using ImageTTFText()

	ImageTTFText($image, $size, $angle, $x, $y, $color, $font, $text);

where $size is the size in pixels (GD1) or points (GD2), $angle is in degrees from 3 o'clock increasing counter-clockwise, $x,$y specify the lower left corner of the text, $font is the absolute path to the font binary, and $text is the text to diaplay.

To assist in determining the length of text, for centering for example, use ImageTTFBBox()

	$array = ImageTTFBBox($size, $angle, $font, $text);

which calculates and returns an array with 8 elements representing four points making the bounding box of the text:

0 	lower left corner, X position
1 	lower left corner, Y position
2 	lower right corner, X position
3 	lower right corner, Y position
4 	upper right corner, X position
5 	upper right corner, Y position
6 	upper left corner, X position
7 	upper left corner, Y position

A GD function reference is http://us2.php.net/manual/en/ref.image.php


Send mail to the Webmaster

logo This site best viewed with a browser
Warning: This is a Debian centric site and MAY contain peanuts.
Many thanks to Debra Lynn and Ian Murdock for making Debian possible
First created Dec 14, 2008 ~ Last revised February 13, 2009

Valid XHTML 1.0 Strict Valid CSS!