首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP GD 繪圖實戰:支援中英文混排的圖片生成完整範例

     編輯:PHP 相關知識

功能簡介

本範例展示如何使用 PHP GD 擴展生成支援中英文混排的 PNG 圖片,適用於驗證碼、圖片浮水印、動態簽名檔等場景。核心技術點包括:TrueColor 畫布建立、TTF 字體載入、透明背景處理、文字陰影效果。

完整程式碼(可直接複製使用)

<?php
// 設定輸出為 PNG 圖片
header("Content-type: image/png");
header("Cache-Control: no-cache");

// 要繪製的文字
$zh_text = "黑體";
$en_text = "Test";

// 字體檔案(建議中英文分開,中文字體內建英文通常不好看)
$zh_font = "simhei.ttf";   // 黑體
$en_font = "arial.ttf";    // Arial

// 建立 400x400 TrueColor 畫布
$im = imagecreatetruecolor(400, 400);
// 或載入現有背景圖:$im = imagecreatefrompng("background.png");

// 定義顏色
$white = imagecolorallocate($im, 255, 255, 255);
$grey  = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

// 填充白底並設為透明色(關鍵步驟!)
imagefill($im, 0, 0, $white);
imagecolortransparent($im, $white);
// 以上兩行解決 imagecreatetruecolor 預設黑底問題,經 Firefox 3 / IE 7 測試通過

// 繪製英文文字(含陰影示範)
// imagettftext($im, 20, 0, 11, 21, $grey, $en_font, $en_text); // 陰影層
imagettftext($im, 12, 0, 100, 120, $black, $en_font, $en_text); // 主文字

// 輸出並釋放資源
imagepng($im);
imagedestroy($im);
?>

關鍵技術點解析

1. 透明背景處理

imagecreatetruecolor() 建立的畫布預設為黑色。先 imagefill() 填白,再 imagecolortransparent() 將白色設為透明色,即可得到透明背景圖片。

2. 中英文字體分離

中文字體(如宋體、黑體)內建的英文字形通常較差,建議分別指定 $zh_font、$en_font。字體檔可從 C:\Windows\Fonts 複製到專案目錄。

3. 文字陰影效果

先以灰色在目標位置偏移 1-2 像素繪製,再以主色彩在原位置繪製,即可產生立體陰影。

4. 擴展應用

  • 驗證碼:加入隨機字串、干擾線、噪點
  • 浮水印:載入目標圖片 imagecreatefromjpeg(),疊加文字後輸出
  • 動態簽名檔:結合使用者資料、統計數字即時生成

常見問題排查

  • 輸出圖片失敗 → 暫時註解 header() 查看錯誤訊息
  • 中文顯示亂碼/方塊 → 確認字體檔路徑正確、檔案編碼為 UTF-8
  • 字體找不到 → 使用絕對路徑或 realpath() 確認

這份範例提供了基礎框架,根據需求微調即可快速投入生產環境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved