<?php
/**
* 绘制柱状图
* @param string $valueStr
* @return null
*/
function drawHistogram($valueStr){
$yValues = explode(",",$valueStr);
$hmax = max($yValues);
$ppix = 150/$hmax;
//计算柱状图高度
foreach ($yValues as $key => $value) {
$h[$key] = 190-$value*$ppix;
}
$endX = 30 + count($yValues)*30;
//创建一个img
$img = imagecreate(755,210);
//背景
$bgc = imagecolorallocate ($img, 245, 250, 254);
//黑色
$bc = imagecolorallocate($img,0,0,0);
//画竖轴
imageline($img,15,30,15,189, $bc);
//画横轴
imageline($img,15,190,$endX,190, $bc);
//画竖轴点
for($i=39,$j=10;$i<189;$i=$i+15,$j--){
imageline($img,13,$i,15,$i, $bc);
imagestring($img,1,1,$i-4,$j."x", $bc);
}
//画横轴点
$t = true;
for($i=31,$j=29;$i<$endX;$i=$j+1,$j=$j+15){
if($t){
$x=$i;
$t=false;
}else{
$x=$i+1;
$t=true;
}
imageline($img,$x,190,$x,192, $bc);
}
//竖轴标记
$x = ceil($hmax/10);
imagestring($img,2,10,15,"X=".$x,$bc);
//竖轴标记
//0点
foreach ($h as $key => $height) {
$width = 30*($key+1);
$color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagefilledrectangle($img,1+$width,$height,15+$width,189,$color);
imagestring($img,1,1+$width,$height-10,$yValues[$key],$color);
imagechar($img,1,6+$width,195,$key,$bc);
}
//加个边框 加了之后不好看
//imagerectangle($img, 0, 0, 754, 209, $bc);
imagepng($img);
imagedestroy($img);
}
header("Content-type: image/png");
$valueStr = isset($_GET['str'])?$_GET['str']:"";
if($valueStr){
drawHistogram($valueStr);
}
?>
php GD绘制柱状图
最新推荐文章于 2021-03-09 22:20:09 发布