A-A+

php GD库饼状图生成接口源码

2012年07月06日 软件开发 暂无评论

GD库是一个php处理图像图片的扩展库,GD库提供了一系列的用来处理图图片的API,使用GD库可以处理图片,或者生成图片,在网站上GD库通常用来生成缩略图,或者对图片加水印等,对于目前最新版的PHP版本来说,生成缩略图或加水印基本上已经用不上专门的GD库来处理了,php可以直接处理简单的图片应用,比如提到的处理图片缩略图,为图片加水印,图片验证码等,而目前PHP 的 GD 图最多的应用应该是饼状图或者是统计图等,下面是一个php GD库饼状图生成的一个接口源码,直接将其运行,可以生成一个蓝色为主的饼状图。

程序运行预览图:

[code lang="php"]
strlen($pts[$i]) ? $tlen : strlen($pts[$i]);
}
//最短边
$min_wh = ($w-2*($tlen+8)*ImageFontWidth(2))>($h-10) ? $h : ($w
-2*($tlen+8)*ImageFontWidth(2));

//创建图片
$im = imagecreate($w,$h);
//图片背景色为白色
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
ImageFill($im,0,0,$white);
//圆心坐标
$cx = $w/2;
$cy = $h/2+20;
//圆外接矩形的宽和高
$cw = $min_wh-65;
$ch = $min_wh-65;

$start = 0;
$end = 0;
for ($i=0; $i<$cnt; $i++){ //扇形的颜色 $color = $i>=43 ? imagecolorallocate($im, rand(0,255), ran
d(0,255), rand(0,255)) : imagecolorallocate($im, $color_arr[$i
][0], $color_arr[$i][1], $color_arr[$i][2]);
$color = imagecolorallocate($im, $color_arr[$i][0], $color_a
rr[$i][1], $color_arr[$i][2]);
//起始角度和结束角度
$start = $end;
$end = $start + $points[$i]/$total*360;
imagefilledarc($im, $cx, $cy, $cw, $ch, $start, $end, $colo
r, IMG_ARC_PIE);
$notel1x = $cx+cos(deg2rad( $start/2+$end/2 ))*$cw/2;
$notel1y = $cy+sin(deg2rad( $start/2+$end/2 ))*$cw/2;
$notel2x = $cx+cos(deg2rad( $start/2+$end/2 ))*($cw/2+10);
$notel2y = $cy+sin(deg2rad( $start/2+$end/2 ))*($cw/2+10);
imageline($im,$notel1x,$notel1y,$notel2x,$notel2y,$black);
$str = strlen( $pts[$i] ) ? $pts[$i]."(".(substr($points[$
i]/$total*100,0,5))."%)" : ($i+1)."(".(substr($points[$i]/$to
tal*100,0,5))."%)";
if ($notel2x > $notel1x ) {
$notel3x = $notel2x+10;
$notestrx = $notel2x+10;
}else {
$notel3x = $notel2x-10;
$notestrx = $notel2x-10-ImageFontWidth(2)*strlen($str);
}
$notel3y = $notel2y;
$notestry = $notel2y-10;
imageline($im,$notel2x,$notel2y,$notel3x,$notel3y,$black);
imagestring($im,2,$notestrx,$notestry,$str,$black);
}

$wf5 = ImageFontWidth(5);
$t_len = $wf5 * strlen($title);
//echo $cw.' '.$ch;die();
imagestring($im, 5, $w/2-$t_len/2, 5, $title, $black);
// flush image
header('Content-type: image/gif');
imagegif($im);
imagedestroy($im);
?>
[/code]

标签:

给我留言