12

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

i.e. "احسان"

Bruce Aldridge
  • 2,907
  • 3
  • 23
  • 30
Ehsan
  • 2,273
  • 8
  • 36
  • 70

4 Answers4

2

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

Behzadsh
  • 851
  • 1
  • 14
  • 30
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;
}
?>
Morteza Soleimani
  • 2,652
  • 3
  • 25
  • 44
1

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

Community
  • 1
  • 1
Nasser Al-Wohaibi
  • 4,562
  • 2
  • 36
  • 28
0

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); 
Husni
  • 1,045
  • 9
  • 12