Web 報表常需動態生成圖表。本文實作一個純 PHP GD 庫的長條圖類別,支援:自動縮放、多資料系列、圖例、標題、座標軸標籤、數值標註、自適應畫布、輸出 PNG/JPEG/Base64。無需外部擴展,部署簡單。
<?php
declare(strict_types=1);
class BarChart
{
private array $data = []; // [[label => value, ...], ...]
private array $seriesLabels = []; // 系列名稱
private array $colors = []; // 系列顏色
private string $title = '';
private string $xLabel = '';
private string $yLabel = '';
private int $width = 800;
private int $height = 500;
private int $margin = 60;
private bool $showValues = true;
private bool $showLegend = true;
private bool $showGrid = true;
private int $fontSize = 10;
private string $fontPath = __DIR__ . '/fonts/DejaVuSans.ttf';
// 內部計算屬性
private int $chartWidth;
private int $chartHeight;
private float $maxValue = 0;
private float $scale = 1.0;
public function __construct(array $config = [])
{
foreach ($config as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
$this->initColors();
}
private function initColors(): void
{
// 預設調色盤:色盲友善
$this->colors = [
'#4e79a7', '#f28e2b', '#e15759', '#76b7b2', '#59a14f',
'#edc949', '#b07aa1', '#ff9da7', '#9c755f', '#bab0ac'
];
}
// 設定資料:支援多系列
// $data = [
// '系列A' => ['Jan' => 10, 'Feb' => 20, ...],
// '系列B' => ['Jan' => 15, 'Feb' => 25, ...],
// ]
public function setData(array $data): self
{
$this->data = $data;
$this->seriesLabels = array_keys($data);
$this->calculateScale();
return $this;
}
public function setTitle(string $title): self { $this->title = $title; return $this; }
public function setLabels(string $xLabel, string $yLabel): self { $this->xLabel = $xLabel; $this->yLabel = $yLabel; return $this; }
public function setSize(int $width, int $height): self { $this->width = $width; $this->height = $height; return $this; }
public function setShowValues(bool $show): self { $this->showValues = $show; return $this; }
public function setShowLegend(bool $show): self { $this->showLegend = $show; return $this; }
public function setFont(string $path, int $size = 10): self { $this->fontPath = $path; $this->fontSize = $size; return $this; }
private function calculateScale(): void
{
$this->maxValue = 0;
foreach ($this->data as $series) {
foreach ($series as $value) {
if (is_numeric($value)) {
$this->maxValue = max($this->maxValue, (float)$value);
}
}
}
// 留白 10%
$this->maxValue *= 1.1;
// 計算繪圖區域
$this->chartWidth = $this->width - 2 * $this->margin;
$this->chartHeight = $this->height - 2 * $this->margin - ($this->title ? 30 : 0) - ($this->showLegend ? 30 : 0);
$this->scale = $this->chartHeight / max($this->maxValue, 1);
}
public function render(): GdImage
{
$img = imagecreatetruecolor($this->width, $this->height);
// 背景
$white = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $white);
// 分配顏色
$black = imagecolorallocate($img, 0, 0, 0);
$gray = imagecolorallocate($img, 200, 200, 200);
$darkGray = imagecolorallocate($img, 100, 100, 100);
$seriesColors = [];
foreach ($this->colors as $hex) {
$seriesColors[] = $this->hexToColor($img, $hex);
}
// 繪製標題
$yOffset = $this->margin;
if ($this->title) {
$this->drawText($img, $this->title, $this->width / 2, $yOffset, $black, $this->fontSize + 4, 'center');
$yOffset += 30;
}
$chartTop = $yOffset;
$chartBottom = $chartTop + $this->chartHeight;
$chartLeft = $this->margin;
$chartRight = $chartLeft + $this->chartWidth;
// 繪製 Y 軸網格線與標籤
$steps = 5;
for ($i = 0; $i <= $steps; $i++) {
$value = $this->maxValue * $i / $steps;
$y = $chartBottom - ($value / $this->maxValue) * $this->chartHeight;
// 網格線
if ($this->showGrid && $i > 0) {
imageline($img, $chartLeft, $y, $chartRight, $y, $gray);
}
// Y 軸標籤
$label = $this->formatNumber($value);
$this->drawText($img, $label, $chartLeft - 10, $y, $darkGray, $this->fontSize, 'right');
}
// 繪製 X 軸與長條
$seriesCount = count($this->data);
$labels = array_keys(reset($this->data)); // 取第一系列的標籤
$labelCount = count($labels);
$groupWidth = $this->chartWidth / $labelCount;
$barWidth = $groupWidth / ($seriesCount + 1) * 0.8; // 留 20% 間距
$groupPadding = ($groupWidth - $barWidth * $seriesCount) / ($seriesCount + 1);
foreach ($this->data as $seriesIndex => $series) {
$color = $seriesColors[$seriesIndex % count($seriesColors)];
foreach ($labels as $labelIndex => $label) {
$value = $series[$label] ?? 0;
$barHeight = ($value / $this->maxValue) * $this->chartHeight;
$x = $chartLeft + $labelIndex * $groupWidth + $groupPadding + $seriesIndex * ($barWidth + $groupPadding);
$y = $chartBottom - $barHeight;
$x2 = $x + $barWidth;
$y2 = $chartBottom;
// 繪製長條 (圓角矩形模擬)
imagefilledrectangle($img, $x, $y, $x2, $y2, $color);
// 數值標籤
if ($this->showValues && $value > 0) {
$text = $this->formatNumber($value);
$textX = $x + $barWidth / 2;
$textY = $y - 5;
$this->drawText($img, $text, $textX, $textY, $black, $this->fontSize - 1, 'center');
}
}
}
// X 軸標籤
foreach ($labels as $index => $label) {
$x = $chartLeft + $index * $groupWidth + $groupWidth / 2;
$this->drawText($img, $label, $x, $chartBottom + 20, $darkGray, $this->fontSize, 'center');
}
// X/Y 軸標題
if ($this->xLabel) {
$this->drawText($img, $this->xLabel, $this->width / 2, $this->height - 10, $black, $this->fontSize + 1, 'center');
}
if ($this->yLabel) {
$this->drawText($img, $this->yLabel, 15, $this->height / 2, $black, $this->fontSize + 1, 'center', 90);
}
// 圖例
if ($this->showLegend) {
$legendY = $chartBottom + 45;
$legendX = $this->margin;
$itemWidth = $this->chartWidth / $seriesCount;
foreach ($this->seriesLabels as $index => $label) {
$color = $seriesColors[$index % count($seriesColors)];
$itemX = $legendX + $index * $itemWidth;
// 色塊
imagefilledrectangle($img, $itemX, $legendY, $itemX + 15, $legendY + 15, $color);
// 文字
$this->drawText($img, $label, $itemX + 20, $legendY + 12, $black, $this->fontSize, 'left');
}
}
// 邊框
imagerectangle($img, $chartLeft, $chartTop, $chartRight, $chartBottom, $darkGray);
return $img;
}
private function drawText(GdImage $img, string $text, float $x, float $y, int $color, int $size, string $align = 'left', int $angle = 0): void
{
$box = imagettfbbox($size, $angle, $this->fontPath, $text);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];
switch ($align) {
case 'center': $x -= $textWidth / 2; break;
case 'right': $x -= $textWidth; break;
}
$y += $textHeight / 2;
imagettftext($img, $size, $angle, $x, $y, $color, $this->fontPath, $text);
}
private function hexToColor(GdImage $img, string $hex): int
{
$hex = ltrim($hex, '#');
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
return imagecolorallocate($img, $r, $g, $b);
}
private function formatNumber(float $num): string
{
if ($num >= 1000000) return number_format($num / 1000000, 1) . 'M';
if ($num >= 1000) return number_format($num / 1000, 1) . 'K';
return number_format($num, $num == (int)$num ? 0 : 1);
}
// 輸出方法
public function outputPng(): void
{
header('Content-Type: image/png');
imagepng($this->render());
}
public function outputJpeg(int $quality = 90): void
{
header('Content-Type: image/jpeg');
imagejpeg($this->render(), null, $quality);
}
public function savePng(string $path): bool
{
return imagepng($this->render(), $path);
}
public function toBase64(): string
{
ob_start();
imagepng($this->render());
$data = ob_get_clean();
return 'data:image/png;base64,' . base64_encode($data);
}
}
?>
<?php
require 'BarChart.php';
// 月度銷售資料
$data = [
'2024 Q1' => ['1月' => 120, '2月' => 150, '3月' => 180],
'2024 Q2' => ['4月' => 200, '5月' => 220, '6月' => 250],
'2024 Q3' => ['7月' => 190, '8月' => 210, '9月' => 230],
];
$chart = new BarChart([
'width' => 1000,
'height' => 600,
'title' => '2024 年季度銷售趨勢',
'xLabel' => '月份',
'yLabel' => '銷售額 (萬元)',
'fontPath' => __DIR__ . '/fonts/msjh.ttc', // 微軟正黑體支援中文
'fontSize' => 11,
]);
$chart->setData($data)
->setShowValues(true)
->setShowLegend(true)
->savePng('sales_chart.png');
// 或直接輸出到瀏覽器
// $chart->outputPng();
// 嵌入 HTML
// echo '
';
?>
.ttf, .ttc)msjh.ttc、思源黑體 SourceHanSansTC-Regular.otfapt-get install fonts-wqy-zenhei fonts-noto-cjk--with-freetype (現代版本預設啟用)純 PHP GD 實作長條圖無需外部依賴,部署極簡。核心在於:座標系轉換 (資料值 ↔ 畫布像素)、自動縮放計算、多系列佈局、文字渲染對齊。本文 BarChart 類別提供完整功能與擴充彈性,可直接用於報表系統、儀表板、定時生成靜態圖片等場景。大規模高併發建議改用前端圖表庫 (Chart.js, ECharts, ApexCharts) 由瀏覽器渲染,減輕伺服器負載。