萬盛學電腦網

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

PHP GD 圖片動態生成:驗證碼、水印、文字繪製完整實作指南

核心流程:建立畫布 → 分配顏色 → 繪製 → 輸出 → 銷毀

<?php
// 入口檢查
if (isset($gd) && $gd == 1 && !empty($txt)) {
    header("Content-Type: image/png");
    
    // 解碼文字 (假設經過加密傳輸)
    $txt = urldecode(phpcms_auth($txt, 'DECODE', AUTH_KEY));
    
    // 畫布尺寸:字元寬度估算 9px
    $width = strlen($txt) * 9;
    $height = 16;
    $im = @imagecreate($width, $height) or die("GD 初始化失敗");
    
    // 顏色分配 (背景、邊框、文字)
    $bgColor = imagecolorallocate($im, 255, 255, 255); // 白底
    $borderColor = imagecolorallocate($im, 234, 185, 95); // 金邊框
    $textColor = imagecolorallocate($im, 0x00, 0x00, 0x00); // 黑字
    
    // 字型選擇:中文用 TTF,英數用內建字型
    $fontFile = PHPCMS_ROOT . 'include/fonts/simfang.ttf';
    if (file_exists($fontFile) && !preg_match('/^[a-z0-9@.]+$/i', $txt)) {
        // 中文路徑:需轉 UTF-8 供 TTF 使用
        $txt = iconv('GB2312', 'UTF-8', $txt);
        imagettftext($im, 10, 0, 0, 12, $textColor, $fontFile, $txt);
    } else {
        // 英數路徑:內建字型 1-5
        $fontType = intval($fontType ?? 2);
        imagestring($im, $fontType, 0, 0, $txt, $textColor);
    }
    
    // 輸出與清理
    imagepng($im);
    imagedestroy($im);
}
?>

關鍵函數說明

函數用途注意事項
imagecreate(w,h)建立調色盤圖片 (256 色)較舊,建議用 imagecreatetruecolor() (真彩色)
imagecreatetruecolor(w,h)建立真彩色圖片 (1677 萬色)現代標準,支援 Alpha 透明
imagecolorallocate()分配顏色索引真彩色圖直接用 RGB 值
imagecolorallocatealpha()分配帶透明度顏色 (0-127)127 完全透明,需 imagesavealpha($im, true)
imagettftext()TrueType 字型繪文字需 FreeType 支援、字體檔路徑正確、文字編碼 UTF-8
imagestring()內建字型繪文字 (1-5 號)僅支援 Latin-1,不支援中文
imagepng()/jpeg()/gif()輸出圖片輸出前需送正確 Content-Type Header
imagedestroy()釋放記憶體長時間腳本必須呼叫,防止記憶體洩漏

進階範例:帶透明背景的文字圖片

<?php
header('Content-Type: image/png');
$text = 'Hello 中文';
$font = __DIR__ . '/fonts/msjh.ttf';

$im = imagecreatetruecolor(300, 80);
imagesavealpha($im, true);
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);

$color = imagecolorallocate($im, 33, 33, 33);
imagettftext($im, 24, 0, 10, 50, $color, $font, $text);

imagepng($im);
imagedestroy($im);
?>

常見坑點與對策

  • 中文亂碼: 來源編碼 (GB2312/UTF-8) 與 iconv 目標編碼必須一致,字體檔需包含對應字符。
  • 字體找不到: 使用絕對路徑 __DIR__ . '/fonts/...',確認 Web 使用者讀取權限。
  • 記憶體耗盡: 大圖處理需調大 memory_limit,處理完立即 imagedestroy()。
  • GD 未安裝: php -m | grep gd 檢查,或 function_exists('imagecreatetruecolor') 運行時判斷。
copyright © 萬盛學電腦網 all rights reserved