PHP 函数 imagettftext() 和 unicode

标签 php unicode gd

我正在使用 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/

相关文章:

php - Laravel 查询在 JSON 字段中选择列表条目

php - Cookie 或 JavaScript

java - 我如何从android中的应用程序发送阿拉伯语单词并在阿拉伯语的mysql数据库上恢复?

python - 已解码字符串出现 Unicode 错误?

php - IMG_FILTER_COLORIZE 问题

php - 在 PHP 中,为什么 imagecreatefromjpeg "not a jpeg file"更改为 fatal error ?

php - mysql_real_escape_string 的缺点?

java - 打印 unicode 代码而不是字符

php - 实现这种图像效果的最佳方式?使用 PHP GD 还是 JS Canvas?

php - 插入查询 If 语句 PHP