很多開發者一聽到「PHP 畫圖」就想到 GD 庫,其實對於簡單的柱狀圖,巧用 HTML <table> 配合 CSS 即可輕鬆實現,零依賴、效能極佳。本文先展示這個「偷懶」技巧,再正式進入 GD 庫的世界。
<?php
$data = array(150, 110, 125, 180, 160, 175, 230, 220); // 範例數據
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
td { font-size: 9pt; font-family: sans-serif; }
</style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="bottom"> <!-- (1) 底部對齊,關鍵! -->
<?php for ($i = 0; $i < count($data); $i++) { ?>
<td align="center">
<table height="<?php echo $data[$i]; ?>" border="0" cellpadding="0" cellspacing="0"> <!-- (2) 用 table height 控制柱高 -->
<tr>
<td bgcolor="#3F7F9F" width="40"></td> <!-- (3) 柱體顏色 -->
</tr>
</table><br>
<font color="#3F7F9F"><?php echo $data[$i]; ?></font> <!-- (4) 顯示實際數值 -->
</td>
<?php } ?>
</tr>
</table>
</body>
</html>
valign="bottom" 放在 <tr> 上,讓整行單元格內容底部對齊,柱狀圖才會整齊「站立」在地面上。<table height="..."> 直接將數據值作為高度。注意:真實專案中數據範圍不一,需先按比例縮放(如 height="<?php echo floor($data[$i]/25); ?>")。bgcolor 定義柱體顏色。若需每根柱子不同顏色,可在迴圈中從顏色陣列取值。將內層 <td> 的 bgcolor 改為 background="pattern.gif",即可擁有紋理柱狀圖,視覺效果大增。
當需要圓餅圖、折線圖、驗證碼、水印、動態縮圖等複雜圖形時,HTML 表格就力不從心了,必須使用 GD 庫。
<?php
// 1. 輸出 HTTP 標頭,告訴瀏覽器這是圖片
header("Content-type: image/png");
// 2. 建立畫布 (寬 50, 高 100)
$im = imagecreate(50, 100); // 返回畫布資源 ID ($im)
// 3. 分配顏色 (第一個分配的自動成為背景色)
$black = imagecolorallocate($im, 0, 0, 0); // 背景:黑
$red = imagecolorallocate($im, 255, 192, 192); // 畫筆:淡紅
// 4. 繪製圖形
imageline($im, 10, 20, 45, 85, $red); // 從 (10,20) 畫線到 (45,85)
// 5. 輸出圖片
imagepng($im); // 直接輸出瀏覽器
// 若要存檔:imagepng($im, "test.png");
// 6. 釋放資源
imagedestroy($im);
?>
imagecolorallocate 為當前畫布註冊一個顏色索引,後續繪圖函數使用此索引。imagepng/imagejpeg/imagegif,第二參數為檔名時存檔,省略則輸出瀏覽器。imagedestroy 釋放畫布佔用的記憶體,長期運行腳本必須呼叫。下一篇將深入講解:
imagecreatetruecolor) 與抗鋸齒。imagettftext FreeType 字體)。ob_start) 實現「網頁中嵌入圖片」。