imagestring() 僅支援英文(內建字體)<?php
$im = imagecreatetruecolor(300, 200);
$red = imagecolorallocate($im, 255, 0, 0);
$str = "hello,world";
imagestring($im, 5, 30, 60, $str, $red); // 第2參數 1-5 為字體大小
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
缺點: 僅 5 種固定字體大小、僅支援 ASCII、僅水平輸出、無法指定字體檔案。
imagettftext() 完美支援中英文(TrueType 字體)<?php
$im = imagecreatetruecolor(300, 200);
$red = imagecolorallocate($im, 255, 0, 0);
// 關鍵:檔案編碼若為 GBK,需轉 UTF-8 才能正確渲染中文
$str = iconv("gb2312", "utf-8", "北京,你早!hello,world");
// imagettftext(畫布, 字體大小, 角度, x, y, 顏色, 字體檔路徑, 文字)
imagettftext($im, 12, rand(0,20), 20, 100, $red, "simhei.ttf", $str);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
| 特性 | imagestring() | imagettftext() |
|---|---|---|
| 中文支援 | ❌ 亂碼 | ✅ 完美 |
| 字體選擇 | 內建 5 種固定 | 任意 .ttf/.ttc 字體檔 |
| 字體大小 | 1-5 號 | 任意像素值 |
| 旋轉角度 | 固定水平 | 任意角度(度) |
| 抗鋸齒 | 無 | 自動抗鋸齒 |
iconv("gb2312", "utf-8", $str) 轉換simhei.ttf 黑體、msyh.ttf 微軟雅黑)array imagettftext ( resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text )
返回值為包含 8 個座標點的陣列(文字邊界框四角),可用於精確佈局計算。