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

PHP GD 繪圖進階:圖片上繪製中英文文字完整指南

     編輯:PHP 相關知識

PHP GD 繪圖進階:圖片上繪製中英文文字完整指南

方案一: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 號任意像素值
旋轉角度固定水平任意角度(度)
抗鋸齒無自動抗鋸齒

中文亂碼根因與解決

  • PHP 內部字串編碼需為 UTF-8
  • 原始碼檔案若為 GBK/Big5,必須 iconv("gb2312", "utf-8", $str) 轉換
  • 字體檔需包含中文字符(如 simhei.ttf 黑體、msyh.ttf 微軟雅黑)
  • 生產環境建議統一專案編碼為 UTF-8,避免轉換額外開銷

函數簽名

array imagettftext ( resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string $text )

返回值為包含 8 個座標點的陣列(文字邊界框四角),可用於精確佈局計算。

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