3

I want to create an image with a text on it with php gd library.

everything is fine, but when I try to write a word from a right to left connected language (like Persian ) using imagefttext(), my text is rendering from left to right (inverse) and the chars are not connected any more .

example of connected chars : ماه example of not connected chars : م ا ه

Here is my code :

    header('Content-Type: image/jpeg');
    $thumb_path = "...";
    $font_path = "..."
    $img = imagecreatefromjpeg($thumb_path);
    $color = "...";
    // __month is a Persian word :  ( م ا ه -->  ماه )
    $text = $months." ".__month;
    imagefttext($img,29, 10, 230, 135, $color, $font_path, $text); // <--
    imagejpeg($img);

The rendered image :

month

I know my problem is not encoding.because I already tried this :

$text = mb_convert_encoding($text, "HTML-ENTITIES", "UTF-8");

And the result is the same.

there are some library available that maybe can solve this problem. and I know that most of you are not familiar with Persian or Arabic languages, but my question is why gd does not support right to left connected languages natively ?

could this be a bug in gd library ?

Alireza Fallah
  • 4,609
  • 3
  • 31
  • 57

2 Answers2

8

Seems that nothing helps (setting correct locale), native PHP support is buggy, that's probably why 3rd party package was created:

Use php-gd-farsi

Works as a charm:

enter image description here

Just copy the library to your PHP directory (don't have to be the admin). The usage is simple:

// init:
include('php-gd-farsi-master/FarsiGD.php');
$gd = new FarsiGD();

....
// then convert your text:
$tx = $gd->persianText($str, 'fa', 'normal');

You don't even have to set the correct locale! :-)

Whole example code:

<?php

include('php-gd-farsi-master/FarsiGD.php');

$gd = new FarsiGD();

// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
//$font_file = './Vera.ttf';
$font_file = './cour.ttf';

// Draw the text 'PHP Manual' using font size 13
$text = imagecreatetruecolor(200, 60);
imagefilledrectangle($text, 0, 0, 200, 60, $red);
$str = '**ماه**';
$tx = $gd->persianText($str, 'fa', 'normal');
imagefttext($text, 24, 10, 10, 50, $black, $font_file,$tx );
$im = $text;

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>
Community
  • 1
  • 1
Tomas
  • 57,621
  • 49
  • 238
  • 373
0

Do you have locale correctly set up?

Looking at the table of locales, the persian should be probably Farsi - fa_IR.UTF-8 from the package fa_utf8. Don't forget to check if it has been set correctly too:

$rv = setlocale(LC_ALL, "fa_IR.UTF-8");
var_dump($rv);

Edit: tried it and it doesn't seem to help either.

Tomas
  • 57,621
  • 49
  • 238
  • 373