函數簽名
function timage(
$graphdata, // 百分比陣列 (Y 軸)
$label, // X 軸標籤陣列
$data, // 實際數值陣列 (Y 軸)
$graphwidth, // 圖表寬度
$graphheight, // 圖表高度
$graphscale, // 高度縮放因子 (=$graphheight/100)
$graphfont, // 字體編號 (1-5)
$bg, // 背景色 RGB 陣列
$text, // 文字色 RGB 陣列
$grid, // 格線色 RGB 陣列
$bar, // 長條色 RGB 陣列
$bz // 備註文字 (不支援中文)
)
完整實作
function timage($graphdata,$label,$data,$graphwidth,$graphheight,$graphscale,$graphfont,$bg,$text,$grid,$bar,$bz) {
header("Content-type: image/gif");
$im = imagecreate($graphwidth+50, $graphheight+50);
$bgc = imagecolorallocate($im, $bg[0],$bg[1],$bg[2]);
$tc = imagecolorallocate($im, $text[0],$text[1],$text[2]);
$gc = imagecolorallocate($im, $grid[0],$grid[1],$grid[2]);
$bc = imagecolorallocate($im, $bar[0],$bar[1],$bar[2]);
$glw = imagefontwidth($graphfont)*3+1;
$glh = imagefontheight($graphfont);
imageline($im, $glw, 0, $glw, $graphheight-1, $gc); // Y 軸
imageline($im, 0, $graphheight-1, $graphwidth-1, $graphheight-1, $gc); // X 軸
// Y 軸刻度與數值
for ($i=0; $i<$graphheight; $i+=$graphheight/10) {
imagedashedline($im, 0, $i, $graphwidth-1, $i, $gc);
imagestring($im, $graphfont, 0, $i, round(($graphheight-$i)/$graphscale), $tc);
}
$bw = (($graphwidth-$glw)/count($graphdata)) - 30;
foreach ($graphdata as $i => $val) {
$x1 = $glw + ($i+1)*20 + $i*$bw;
$x2 = $x1 + $bw;
$y2 = $graphheight-1;
$y1 = $y2 - $val*$graphscale;
imagefilledrectangle($im, $x1, $y1, $x2, $y2, $bc); // 長條
imagestring($im, $graphfont, $x1, $y1-15, "$val%", $tc); // 頂端百分比
imagestring($im, $graphfont, $x1, $y2, $label[$i], $tc); // X 軸標籤
imagestringup($im, $graphfont, $x1+10, $y1-$glh, $data[$i], $tc); // 垂直實際值
}
imagestring($im, $graphfont, 1, $graphheight+30, $bz, $tc);
imagegif($im);
imagedestroy($im);
}
呼叫範例
$graphdata = array(30, 50, 80, 45);
$label = array('Q1','Q2','Q3','Q4');
$data = array(300, 500, 800, 450);
timage($graphdata, $label, $data, 400, 200, 2, 2,
array(255,255,255), array(0,0,0), array(200,200,200), array(0,0,255),
'2024 年度業績');
注意事項
- 需啟用 GD 擴充模組 (PHP 4.3+ 內建)。
- 輸出為 GIF,若需 PNG/JPEG 改用
imagepng/imagejpeg。
- 中文支援需改用
imagettftext + TrueType 字體。
- 參數陣列長度必須一致,否則會產生警告。