PHP Drawing Example


The GD library is used to draw pictures in PHP. To enable GD, uncomment extension=php_gd2.dll in the configuration file "php.ini".

Let's have an example:

<?PHP
    $width=500;
	$height=300;
	$im = imagecreatetruecolor($width,$height);
	$gray = imagecolorallocate($im, 102, 102, 102);
	$white = imagecolorallocate($im, 255, 255, 255);
	$black = imagecolorallocate($im, 0, 0, 0);
	$blue   = imagecolorallocate($im, 0, 0, 255);
	$red    = imagecolorallocate($im, 255, 0, 0);
	$green  = imagecolorallocate($im, 0, 255, 0);
	imagefill($im,0,0,$white);

	$x_ori = 40;
	$y_ori = 60;
	$y_bottom = 60;
	$xlen = $width - $x_ori - $x_ori * 1.5;
	$ylen = $height - $y_ori - $y_bottom;

	imageline($im,$x_ori,$y_ori+$ylen,$x_ori+$xlen,$y_ori+$ylen,$black);  //x axis bottom
	imageline($im,$x_ori,$y_ori,$x_ori,$y_ori + $ylen,$black);  //y axis left
	imageline($im,$x_ori,$y_ori,$x_ori+$xlen,$y_ori,$black);  //x axis top
	imageline($im,$x_ori+$xlen,$y_ori,$x_ori+$xlen,$y_ori+$ylen,$black);  //y axis right

	imagestring($im,2,$x_ori + $xlen/2 -10,$y_ori + $ylen + 20,"width", $black);
	imagestringup($im,2,$x_ori-20,$y_ori + $ylen/2 + 20,"height", $black);			   
	
	$arry = array(1,50,100,150,200);
	
	for ($i=0;$i<5;$i++)
	{
	    $y = $y_ori + ($arry[$i] - $arry[0]) * $ylen/($arry[4]-$arry[0]);
		   
		$style=array($white,$white,$gray,$white,$white);
		imagesetstyle($im,$style);
		imageline($im,$x_ori+2,$y,$x_ori + $xlen -2,$y,IMG_COLOR_STYLED);
		imagestring($im,2,$x_ori + $xlen + 5,$y-7,number_format($arry[$i]), $black);			   
	}
	
	imagejpeg($im,"gd.jpg",65);
	imagedestroy($im);
?>

The picture looks like follows:
To print the picture on the screen instead of saving it as a file:
<?PHP
    header('Content-type: image/jpeg');
	imagejpeg($im);
?>

Draw line:
imageline($im,x1,y1,x2,y2,color);

Draw dashed line:
$style=array($white,$white,$gray,$white,$white); //dashed style
imagesetstyle($im,$style);
imageline($im,$x_ori+2,$y,$x_ori + $xlen -2,$y,IMG_COLOR_STYLED);

Draw rectangle:
imagerectangle($im,x1,y1,x2,y2,color);

Draw text:
imagestring($im,font,x,y,$string,color);  //draw horizontal text
imagestringup($im,font,x,y,$string,color); //draw vertical text

Draw circle and ellipse:
imageellipse($im,x,y,width,height,color);
imagefilledellipse($im,x,y,width,height,color);

Draw polygon:
<?PHP
$arr=array(15,10,5,20,30,15);
imagepolygon($im,$arr,points,color);	
?>


Click here for complete list of GD functions.