imagettftext() 要求輸入字串為 UTF-8 編碼。若 PHP 原始碼檔案以 GBK/GB2312/Big5 儲存,直接傳入中文會導致亂碼。
iconv() 轉碼<?php
$im = imagecreatefromjpeg('./1.jpg');
$w = imagesx($im);
$h = imagesy($im);
$green = imagecolorallocate($im, 50, 100, 200);
// 關鍵:將 GB2312 字串轉為 UTF-8
$str = iconv('gb2312', 'utf-8', '幸福就在身邊');
imagettftext($im, 16, 0, 200, 100, $green, './simhei.ttf', $str);
header("Content-type: image/jpeg");
imagejpeg($im);
imagedestroy($im);
?>
mb_convert_encoding() 替代 iconv(),前者對非法字元容錯更好mb_convert_encoding() 範例<?php
/* 轉換內部編碼為 SJIS */
$str = mb_convert_encoding($str, "SJIS");
/* 將 EUC-JP 轉換成 UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");
/* 自動檢測編碼並轉換至 UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");
/* "auto" 擴展為 "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>
mb_convert_encoding() 支援「自動偵測來源編碼」,在來源編碼不確定時極其實用。