萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 庫實戰:繪製帶陰影效果的文字圖片完整教學

前言

GD 庫是 PHP 核心圖形處理擴展,廣泛用於驗證碼生成、圖片水印、報表圖表、社交分享圖等場景。本文通過實際專案案例——微信公眾號空氣質量分享圖生成,詳細講解如何使用 imagettftext() 繪製帶陰影立體感的文字效果。

核心原理:偏移繪製法

GD 庫無內建陰影參數,但可通過疊加繪製實現:

  1. 先用陰影顏色在 (x+1, y+1) 繪製文字
  2. 再用主色在 (x, y) 繪製文字
  3. 視覺上形成右下方 1 像素偏移的陰影效果

完整程式碼實作

<?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() 參數深度解析

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() 返回 falseGD 未編譯 FreeType 支援重新編譯 PHP 加入 --with-freetype-dir,或安裝 php-gd 套件
文字位置偏移異常誤以為 (x,y) 為左上角記住:基線左下角;預留足夠上方空間
輸出圖片模糊JPEG 壓縮品質過低imagejpeg($im, null, 90) 設定品質 90+
記憶體耗盡大尺寸圖片未釋放資源必須呼叫 imagedestroy($im)

生產環境建議

  • 字體授權:商業專案請使用開源字體(思源黑體、Noto 系列)或購買商業授權
  • 效能優化:高併發場景下,考慮使用 Swoole/Workerman 常駐進程複用 GD 資源,或改用 ImageMagick (imagick 擴展)
  • 快取策略:相同參數生成的圖片建議快取(MD5 參數做檔名),避免重複運算

總結

GD 庫雖屬基礎擴展,但掌握 imagettftext() 疊加繪製技巧,即可實現專業級文字陰影、描邊、發光等效果。本文提供的封裝函數可直接整合至專案,支援多行、多樣式、自動換行擴展,滿足大多數動態圖片生成需求。

copyright © 萬盛學電腦網 all rights reserved