我正在使用 PHP 函数 imagettftext() 将文本转换为 GIF 图像。我正在转换的文本具有 Unicode 字符,包括日文。在我的本地机器(Ubuntu 7.10)上一切正常,但在我的虚拟主机服务器上,日语字符被破坏了。是什么导致了差异?所有内容都应编码为 UTF-8。
虚拟主机服务器上的图像损坏: http://www.ibeni.net/flashcards/imagetest.php
从我的本地机器复制正确的图像: http://www.ibeni.net/flashcards/imagetest.php.gif
从我的本地机器复制 phpinfo(): http://www.ibeni.net/flashcards/phpinfo.php.html
从我的虚拟主机服务器复制 phpinfo(): http://example5.nfshost.com/phpinfo
代码:
mb_language('uni');
mb_internal_encoding('UTF-8');
header('Content-type: image/gif');
$text = '日本語';
$font = './Cyberbit.ttf';
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 159, 159, $white);
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $text);
imagegif($im);
imagedestroy($im);
最佳答案
我在使用将在图像中呈现文本并将其输出的脚本时遇到了同样的问题。问题是,由于不同的浏览器(或代码耐久性/偏执狂,无论你想用哪种方式),我无法知道 $_GET
数组中放置了什么编码。
这是我解决问题的方法。
$item_text = $_GET['text'];
# detect if the string was passed in as unicode
$text_encoding = mb_detect_encoding($item_text, 'UTF-8, ISO-8859-1');
# make sure it's in unicode
if ($text_encoding != 'UTF-8') {
$item_text = mb_convert_encoding($item_text, 'UTF-8', $text_encoding);
}
# html numerically-escape everything (&#[dec];)
$item_text = mb_encode_numericentity($item_text,
array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
通过简单地将所有字符(包括多字节 Unicode 字符)更改为它们的 HTML 数字字符实体——“A”,这解决了 imagettftext
无法处理超过 #127 的字符的任何问题对于“A”、“B”对于“B”等——manual page声称支持。
关于PHP 函数 imagettftext() 和 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/198007/