我如何写非英语字符,如阿拉伯语或波斯语字符到一个图像


How can I write Non English Characters such as Arabic or Persian characters into an image?

如何使用PHP GD库将阿拉伯语或波斯语字符写入图像?

。"احسان"

我写了一个基于库的编写器包,我不记得名字了。我修改了库并修复了一些bug。

你可以在这里找到源代码。你也可以通过以下命令来安装它:

composer require quince/persian-gd
  • 波斯语字符
  • 没有问题
  • 这是可定制的
  • 字符串不会溢出图像画布

请测试它,并发送错误报告,建议和…

谢谢

使用此函数将文本传递给imagettftext

<?php
function revUni($text) {
    $wordsArray = explode(" ", $text);
    $rtlCompleteText='';
    for ($i = sizeOf($wordsArray); $i > -1; $i = $i-1) {
        //$lettersArray = explode("|", str_replace(";|", ";", $wordsArray[$i]));
        $lettersArray = explode(";", $wordsArray[$i]);
        $rtlWord='';
        for ($k = sizeOf($lettersArray); $k > -1; $k = $k-1) {
            if (strlen($lettersArray[$k]) > 1) { // make sure its full unicode letter
                $rtlWord = $rtlWord."".$lettersArray[$k].";";
            }
        }
        $rtlCompleteText = $rtlCompleteText." ".$rtlWord;
    }
    return $rtlCompleteText;
}
?>

像数组那样简单地反转阿拉伯字符是行不通的。您需要考虑阿拉伯符号,并用精确的Unicode符号替换它们。查看这里的类似问题和解决方案:将阿拉伯语写入图像

时出错

尝试使用imagettftext

<?php
// http://localhost/test.php?text=احسان
// test.php file
$font = 'C:/Windows/Fonts/Arial.ttf';
$text = $_GET['text'];
// [switch to right to left] 
// try comparing of using this block and not using this block
$rtl = array();
for($i=0; $i<strlen($text); $i+=2) {
    $rtl[] = substr($text, $i, 2);
}
$rtl = array_reverse($rtl);
$rtl = implode($rtl);
$text = $rtl;
// [/switch to right to left]
$im = imagecreatetruecolor(65, 35);
$black = imagecolorallocate($im, 0, 0, 0);  
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 500, 100, $white);  
imagettftext($im, 12, 0, 10, 20, $black, $font, $text);  
header('Content-type: image/png');  
imagepng($im);  
imagedestroy($im);