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

你说的曾经没有我的故事 提交于 2019-12-28 17:30:49

问题


How can I write Arabic or Persian characters to an image using PHP GD library?

i.e. "احسان"


回答1:


Use this function in order to pass text to 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;
}
?>



回答2:


Plainly reversing Arabic characters like an array just won't work. You need to account for Arabic glyphs and substitute each with the exact Unicode symbol. see here for a similar question and a solution: Error while writting Arabic to image




回答3:


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



回答4:


I had write a composer package based on a library, I don't remember the name. I modified the library and fixed some bugs it had.

You can find the source here. and you can also install it with composer by running:

composer require quince/persian-gd
  • It has no issue with Persian character
  • It's customizable
  • The string will not overflow out of the image canvas

Please test it, and send bug reports, suggestion and ...

Thanks



来源:https://stackoverflow.com/questions/7426685/how-can-i-write-non-english-characters-such-as-arabic-or-persian-characters-into

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!