PHP 函数 imagettftext() 和 unicode

2023-12-27

我正在使用 PHP 函数 imagettftext() 将文本转换为 GIF 图像。我正在转换的文本包含 Unicode 字符,包括日语。在我的本地计算机(Ubuntu 7.10)上一切正常,但在我的网络主机服务器上,日语字符被破坏。是什么导致了这种差异?所有内容均应编码为 UTF-8。

虚拟主机服务器上的图像损坏:http://www.ibeni.net/flashcards/imagetest.php http://www.ibeni.net/flashcards/imagetest.php

从我的本地计算机复制正确的图像:http://www.ibeni.net/flashcards/imagetest.php.gif http://www.ibeni.net/flashcards/imagetest.php.gif

从我的本地计算机复制 phpinfo() :http://www.ibeni.net/flashcards/phpinfo.php.html http://www.ibeni.net/flashcards/phpinfo.php.html

从我的虚拟主机服务器复制 phpinfo() :http://example5.nfshost.com/phpinfo http://example5.nfshost.com/phpinfo

Code:

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); 

这是最终对我有用的解决方案:

$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;
    }
}

将字符串转换为 HTML 实体是可行的,只是函数 imagettftext() 不接受命名实体。例如,

&#26085;&#26412;&#35486;

没问题,但是

&ccedil;

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP 函数 imagettftext() 和 unicode 的相关文章

随机推荐