GD 庫是 PHP 核心圖形處理擴展,廣泛用於驗證碼生成、圖片水印、報表圖表、社交分享圖等場景。本文通過實際專案案例——微信公眾號空氣質量分享圖生成,詳細講解如何使用 imagettftext() 繪製帶陰影立體感的文字效果。
GD 庫無內建陰影參數,但可通過疊加繪製實現:
(x+1, y+1) 繪製文字(x, y) 繪製文字<?php
/**
* 生成帶陰影文字的圖片
* @param string $bgImage 背景圖路徑
* @param string $fontFile TTF 字體檔路徑
* @param array $textLines 文字行配置 ['text' => '', 'size' => 0, 'x' => 0, 'y' => 0, 'color' => [], 'shadowColor' => []]
* @param string $outputPath 輸出路徑(空則直接輸出瀏覽器)
*/
function generateShadowTextImage(
string $bgImage,
string $fontFile,
array $textLines,
string $outputPath = ''
): bool
{
// 1. 從背景圖創建畫布
$im = @imagecreatefromjpeg($bgImage);
if (!$im) {
trigger_error("無法載入背景圖: {$bgImage}", E_USER_ERROR);
return false;
}
// 2. 載入字體(需確認檔案存在)
if (!file_exists($fontFile)) {
trigger_error("字體檔不存在: {$fontFile}", E_USER_ERROR);
return false;
}
// 3. 分配顏色
$colors = [];
foreach ($textLines as $i => $line) {
$colors[$i]['main'] = imagecolorallocate($im, ...$line['color']);
$colors[$i]['shadow'] = imagecolorallocate($im, ...$line['shadowColor']);
}
// 4. 繪製每行文字(陰影在前,主文字在後)
foreach ($textLines as $i => $line) {
// 陰影層(偏移 1px)
imagettftext(
$im,
$line['size'],
$line['angle'] ?? 0,
$line['x'] + 1,
$line['y'] + 1,
$colors[$i]['shadow'],
$fontFile,
$line['text']
);
// 主文字層
imagettftext(
$im,
$line['size'],
$line['angle'] ?? 0,
$line['x'],
$line['y'],
$colors[$i]['main'],
$fontFile,
$line['text']
);
}
// 5. 輸出
if ($outputPath) {
$result = imagejpeg($im, $outputPath, 90);
} else {
header('Content-Type: image/jpeg');
$result = imagejpeg($im, null, 90);
}
// 6. 釋放資源
imagedestroy($im);
return $result;
}
// === 使用範例 ===
$bgImage = 'images/3.jpg'; // 背景圖
$fontFile = 'zt.ttf'; // 微軟雅黑或思源黑體等 TTF
$textLines = [
[
'text' => '北京',
'size' => 41,
'x' => 60,
'y' => 100,
'color' => [222, 229, 207], // 淺綠主色
'shadowColor' => [50, 50, 50], // 深灰陰影
],
[
'text' => '空氣質量:輕度污染',
'size' => 43,
'x' => 60,
'y' => 170,
'color' => [222, 229, 207],
'shadowColor' => [50, 50, 50],
],
];
generateShadowTextImage($bgImage, $fontFile, $textLines, 'output/air_quality.jpg');
echo "圖片生成成功!";
?>
imagettftext(
GdImage $image, // 畫布資源
float $size, // 字體大小(單位:點,1pt = 1/72 inch)
float $angle, // 旋轉角度(度),0=水平,>0 逆時針
int $x, // 起始 X 座標(字符左下角基準點)
int $y, // 起始 Y 座標
int $color, // 顏色索引(由 imagecolorallocate 返回)
string $fontfile, // TTF 字體檔完整路徑
string $text // 文字內容(支援 UTF-8)
): array|false
($x, $y) 為字符基線左下角,非左上角。中文通常比英文字符高,視覺上文字會向上延伸。
function imagettftext_wrap(
$im, $size, $angle, $x, $y, $color, $fontfile, $text, $maxWidth, $lineHeight = 1.2
) {
$words = preg_split('/(? $maxWidth && $lines[$currentLine] !== '') {
$currentLine++;
$lines[$currentLine] = $char;
} else {
$lines[$currentLine] = $testLine;
}
}
foreach ($lines as $i => $line) {
$lineY = $y + $i * $size * $lineHeight;
imagettftext($im, $size, $angle, $x, $lineY, $color, $fontfile, $line);
}
return count($lines);
}
| 問題 | 原因 | 解決方案 |
|---|---|---|
| 中文顯示方框/亂碼 | 字體不支援中文或路徑錯誤 | 使用支援中文的 TTF(如微軟雅黑、思源黑體、Noto Sans SC),確認絕對路徑 |
| imagettftext() 返回 false | GD 未編譯 FreeType 支援 | 重新編譯 PHP 加入 --with-freetype-dir,或安裝 php-gd 套件 |
| 文字位置偏移異常 | 誤以為 (x,y) 為左上角 | 記住:基線左下角;預留足夠上方空間 |
| 輸出圖片模糊 | JPEG 壓縮品質過低 | imagejpeg($im, null, 90) 設定品質 90+ |
| 記憶體耗盡 | 大尺寸圖片未釋放資源 | 必須呼叫 imagedestroy($im) |
GD 庫雖屬基礎擴展,但掌握 imagettftext() 疊加繪製技巧,即可實現專業級文字陰影、描邊、發光等效果。本文提供的封裝函數可直接整合至專案,支援多行、多樣式、自動換行擴展,滿足大多數動態圖片生成需求。