本範例展示如何使用 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);
?>
imagecreatetruecolor() 建立的畫布預設為黑色。先 imagefill() 填白,再 imagecolortransparent() 將白色設為透明色,即可得到透明背景圖片。
中文字體(如宋體、黑體)內建的英文字形通常較差,建議分別指定 $zh_font、$en_font。字體檔可從 C:\Windows\Fonts 複製到專案目錄。
先以灰色在目標位置偏移 1-2 像素繪製,再以主色彩在原位置繪製,即可產生立體陰影。
imagecreatefromjpeg(),疊加文字後輸出header() 查看錯誤訊息realpath() 確認這份範例提供了基礎框架,根據需求微調即可快速投入生產環境。