我使用PHP函数imagettftext()将文本转换为GIF图像。我要转换的文本包含Unicode字符,包括日语。在我的本地机器(Ubuntu 7.10)上一切正常,但在我的网络主机服务器上,日语字符却乱七八糟。造成这种差异的原因可能是什么?所有内容都应该编码为UTF-8。
webhost主机服务器上的损坏图像:http://www.ibeni.net/flashcards/imagetest.php
来自本地计算机的正确镜像的副本:http://www.ibeni.net/flashcards/imagetest.php.gif
我本地机器上的phpinfo()的副本:http://www.ibeni.net/flashcards/phpinfo.php.html
来自我的webhost主机服务器的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); 发布于 2008-10-14 16:02:48
以下是最终对我起作用的解决方案:
$text = "你好";
// Convert UTF-8 string to HTML entities
$text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8");
// Convert HTML entities into ISO-8859-1
$text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Convert characters > 127 into their hexidecimal equivalents
$out = "";
for($i = 0; $i < strlen($text); $i++) {
$letter = $text[$i];
$num = ord($letter);
if($num>127) {
$out .= "&#$num;";
} else {
$out .= $letter;
}
}除了imagettftext()函数不接受命名实体之外,将字符串转换为HTML实体是可行的。例如,
日本語是可以的,但是
ç不是。转换回ISO-8859-1,将命名实体转换回字符,但存在第二个问题。imagettftext()不支持值大于127的字符。最后一个for循环将这些字符编码为十六进制。这个解决方案适用于我正在使用的文本(包括日语、中文和葡萄牙语的重音拉丁字符),但我不是100%确定它在所有情况下都有效。
所有这些操作都是必需的,因为imagettftext()在我的服务器上并不真正接受UTF-8字符串。
发布于 2009-12-24 10:23:40
我一直在使用一个在图像中呈现文本并将其输出的脚本遇到同样的问题。问题是,由于不同的浏览器(或代码的顽固性/偏执,无论您如何看待它),我无法知道在$_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');这解决了imagettftext无法处理#127以上字符的任何问题,只需将所有字符(包括多字节Unicode字符)更改为manual page声称支持的HTML数字字符实体-“A”代表"A","B“代表"B”等。
发布于 2010-10-13 16:54:57
我也有同样的问题。将字体从otf转换为ttf很有帮助。您可以使用FontForge (标准存储库中提供)进行转换。
https://stackoverflow.com/questions/198007
复制相似问题