PHP GD 繪圖代碼寫得沒錯,瀏覽器卻顯示「圖片無法顯示」、「圖片包含錯誤」或直接輸出亂碼。核心原因通常只有三類:**GD 擴展未啟用**、**輸出前有內容干擾**、**Header 設置錯誤/缺失**。本文提供系統化排查步驟與標準化代碼模板。
php -m | grep gd 或 phpinfo() 確認 GD Support => enabled、FreeType Support => enabled。<?php,前面**不能有任何字符**(包括空白行、BOM、HTML、echo、var_dump)。ob_clean() 或 ob_end_clean() 清除之前的輸出緩衝。header('Content-Type: image/png')(或 jpeg/gif)。?> 後的換行),建議**省略結束標籤**。<?php
// captcha.php 或 chart.php
// 1. 禁止錯誤輸出到圖片流(生產環境建議關閉 display_errors)
ini_set('display_errors', 0);
error_reporting(E_ALL);
// 2. 清理所有輸出緩衝(關鍵!防止框架/包含文件產生的輸出污染圖片流)
if (ob_get_level()) ob_end_clean();
// 3. 發送正確 Content-Type(必須在任何輸出之前)
header('Content-Type: image/png');
// 可選:防緩存
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
// 4. 繪圖邏輯
$width = 120; $height = 40;
$im = imagecreatetruecolor($width, $height);
// 背景色
$bg = imagecolorallocate($im, 240, 240, 240);
imagefill($im, 0, 0, $bg);
// 文字顏色
$textColor = imagecolorallocate($im, 51, 51, 51);
// 繪製文字(需 FreeType 支持)
$font = __DIR__ . '/fonts/DejaVuSans.ttf'; // 確保字體文件存在
$text = 'ABCD';
imagettftext($im, 20, 0, 15, 30, $textColor, $font, $text);
// 干擾線
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($im, rand(150,200), rand(150,200), rand(150,200));
imageline($im, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $lineColor);
}
// 5. 輸出圖片並銷毀資源
imagepng($im);
imagedestroy($im);
// 6. 結束腳本(不需要 ?>,避免後置空白)
| 現象 | 典型原因 | 修復 |
|---|---|---|
| 瀏覽器顯示亂碼/二進制字符 | 缺少 header('Content-Type: image/png'),瀏覽器按 text/html 解析 | 添加正確 Header,確保在輸出前 |
| 「圖片包含錯誤」/ 破碎圖標 | 圖片數據流前/後有額外字符(空白、BOM、錯誤信息、HTML) | 1. 文件無 BOM 2. 輸出前 ob_end_clean() 3. 省略 ?> 4. 關閉 display_errors |
| 調用 imagefttext/imagettftext 報錯 | GD 未編譯 FreeType 支持,或字體文件路徑錯誤 | 安裝 php-gd 並確保 --with-freetype;字體用絕對路徑 __DIR__ . '/font.ttf' |
| 圖片顯示不全/空白 | 坐標超出畫布、顏色分配失敗、字體大小超出畫布 | 檢查坐標計算,imagecolorallocate 返回 false 時處理 |
| 文件下載同理 | 文件下載輸出前也需 ob_clean(),否則文件損壞 | 同繪圖:輸出前清理緩衝,發送正確 Header,流式輸出 |
ThinkPHP / Laravel / Yii 等框架中,繪圖動作同樣遵循「清理緩衝 → 發 Header → 輸出 → 結束」原則。
<?php
// ThinkPHP 5.x 控制器示例
public function captcha()
{
// 框架可能已有輸出緩衡,必須清理
ob_clean(); // 或 ob_end_clean()
// 使用框架內置驗證碼類(推薦)
// return captcha_img(); // TP5.1+
// 或手動繪圖
header('Content-Type: image/png');
// ... 繪圖代碼 ...
imagepng($im);
imagedestroy($im);
exit; // 關鍵:阻止框架後續模板渲染輸出
}
<?php
// check_gd.php
if (!extension_loaded('gd')) {
die('GD extension NOT loaded. Install: yum install php-gd / apt-get install php-gd');
}
$info = gd_info();
echo "GD Version: {$info['GD Version']}\n";
echo "FreeType Support: " . ($info['FreeType Support'] ? 'YES' : 'NO') . "\n";
echo "JPEG Support: " . ($info['JPEG Support'] ? 'YES' : 'NO') . "\n";
echo "PNG Support: " . ($info['PNG Support'] ? 'YES' : 'NO') . "\n";
echo "GIF Read/Write: " . ($info['GIF Read Support'] && $info['GIF Create Support'] ? 'YES' : 'NO') . "\n";
// 測試實際繪圖
$im = @imagecreatetruecolor(10, 10);
if (!$im) die('imagecreatetruecolor FAILED');
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);
$black = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 5, 0, 0, 'OK', $black);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
PHP GD 繪圖不顯示,**90% 是輸出緩衝污染**。死記公式:無 BOM 文件 → ob_clean() → header(Content-Type) → 繪圖 → 輸出 → exit/省略?>。配合關閉 display_errors、驗證 GD/FreeType 安裝,即可解決所有顯示異常。