本文提供一個完整的 PHP 圖片生成示例,支援中英文混排、TrueType 字體、透明背景與陰影效果,可直接用於驗證碼、水印等場景。
<?php
/*
* Photozero.net 改編自 PHP 參考文檔
*/
// 設置輸出頭,調試時可暫時註釋查看錯誤
header("Content-type: image/png");
header("Cache-Control: no-cache");
// 要輸出的文字
$zh_text = '黑體';
$en_text = 'Test';
// 字體文件(建議中英文使用不同字體)
$zh_font = 'simhei.ttf'; // 中文字體:黑體
$en_font = 'arial.ttf'; // 英文字體:Arial
// 1. 創建真彩色圖像背景 (寬 400, 高 400)
$im = imagecreatetruecolor(400, 400);
// 或者使用現有圖片:$im = imagecreatefrompng('background.png');
// 2. 定義顏色
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
// 3. 填充白色背景並設置透明
imagefill($im, 0, 0, $white);
imagecolortransparent($im, $white); // 關鍵:白色變透明
// 4. 繪製陰影效果(可選)
// imagettftext($im, 20, 0, 11, 21, $grey, $en_font, $en_text);
// 5. 繪製正式文字
imagettftext($im, 12, 0, 100, 120, $black, $en_font, $en_text);
// 中文繪製同理:imagettftext($im, 20, 0, 100, 200, $black, $zh_font, $zh_text);
// 6. 輸出並銷毀
imagepng($im);
imagedestroy($im);
?>
許多開發者遇到 imagecreatetruecolor 背景變黑的問題。解決方案:先填充白色,再將白色設置為透明色:
imagefill($im, 0, 0, $white);
imagecolortransparent($im, $white);
中文字體(如宋體、黑體)內建的英文字形通常較差,建議:
simhei.ttf、simsun.ttc 等arial.ttf、verdana.ttf 等C:\Windows\Fonts 複製到項目目錄先用淺色在偏移位置繪製,再用深色在正確位置繪製,即可產生立體感。
memory_limit,及時 imagedestroy這段代碼雖然功能單一,但構建了圖片生成的標準流程:創建→繪製→輸出→銷毀。掌握此框架,各類圖像動態生成需求皆可快速實現。