首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP函数imagettftext()和unicode

PHP函数imagettftext()和unicode
EN

Stack Overflow用户
提问于 2008-10-13 15:33:39
回答 5查看 24.3K关注 0票数 12

我使用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

代码:

代码语言:javascript
复制
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); 
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2008-10-14 16:02:48

以下是最终对我起作用的解决方案:

代码语言:javascript
复制
$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实体是可行的。例如,

代码语言:javascript
复制
&#26085;&#26412;&#35486;

是可以的,但是

代码语言:javascript
复制
&ccedil;

不是。转换回ISO-8859-1,将命名实体转换回字符,但存在第二个问题。imagettftext()不支持值大于127的字符。最后一个for循环将这些字符编码为十六进制。这个解决方案适用于我正在使用的文本(包括日语、中文和葡萄牙语的重音拉丁字符),但我不是100%确定它在所有情况下都有效。

所有这些操作都是必需的,因为imagettftext()在我的服务器上并不真正接受UTF-8字符串。

票数 13
EN

Stack Overflow用户

发布于 2009-12-24 10:23:40

我一直在使用一个在图像中呈现文本并将其输出的脚本遇到同样的问题。问题是,由于不同的浏览器(或代码的顽固性/偏执,无论您如何看待它),我无法知道在$_GET数组中放入了什么编码。

下面是我是如何解决这个问题的。

代码语言:javascript
复制
$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”等。

票数 12
EN

Stack Overflow用户

发布于 2010-10-13 16:54:57

我也有同样的问题。将字体从otf转换为ttf很有帮助。您可以使用FontForge (标准存储库中提供)进行转换。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/198007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档