使用GD库在图形上发布条形码图像

时间:2012-03-14 16:09:26

标签: php graph gd

我只是想知道如何使用Gd库函数在我的图形上显示具有精确数据数组值的条形,并使用for循环/ for-each循环回复我

帮助绝对值得赞赏

此代码中的混淆注释标记表示我的问题

$array = array(
              "Jan" => 110,
              "Feb" => 130,
              "Mar" => 215,
              "Apr" => 81,
              "May" => 310,
              "Jun" => 110,
              "Jul" => 190,
              "Aug" => 175,
              "Sep" => 850,
              "Oct" => 286,
              "Nov" => 150,
              "Dec" => 196);



$width = 600;
$height = 500;
$margin = 20;
$line_width  = $width-($margin*4)-25-15;
$line_height = $width-$margin;


$max_array_value=max($array);
$min_array_value=min($array);

$im = imagecreate($width,$height);

$red = imagecolorallocate($im,225,0,0);
$black = imagecolorallocate($im,0,0,0);
$white  = imagecolorallocate($im, 255, 255, 255);


// Create rectangle with margin color borders 
imagefilledrectangle($im,$margin,$margin,$width-$margin,$height-$margin,$black);


// Create vertical line
for($i=25;$i<=$line_width;$i+=15){
    imageline($im,$margin,$i,$width-$margin,$i,$white);
}

// Create horizontal line
for($i=25;$i<=$line_height;$i+=15){
    imageline($im,$i,$height-$margin,$i,$margin,$white);
}

$j=480;
for($i=$min_array_value;$i<=$max_array_value;$i+=$min_array_value){
    imagestring($im,3,1,$j-=20,$i,$white);
}


//for Start Confusion here
imagefilledrectangle($im,45 ,400,$width-565,$height-20,$red);
imagefilledrectangle($im,60 ,300,$width-550,$height-20,$red);
//for End Confusion here     

header("Content-type:image/jpeg");
imagepng($im);

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要使用数据循环创建条形图。我的代码不准确,您必须调整参数,直到条形按您想要的方式出现。尝试使用以下内容替换您的混淆部分:

$n = 0;
foreach($array as $k => $v) {
    imagefilledrectangle($im, ($n * 15) + 45, 400, ($n * 15 + 55), 400 - $v, $red);
    $n++;
}