Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write RTL (arabic) text to image with PHP

I would like to generate an image with some text on it, the LTR languages seems to be working fine, but when trying it in arabic, it, simply, didn't work, see the screenshot bellow where I draw 3 text strings with the presented text code

enter image description here

Here my test code (with some comments):

// Create a 300*300 image
$im = imagecreate(300, 300);

// Yellow transparent background and blue text
$bg = imagecolorallocatealpha($im, 255, 255, 0, 45);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write an LTR string
imagestring($im, 5, 250, 100, 'test', $textcolor);

$font = 'DroidKufi-Regular.ttf'; // specify the fonts file
$text = "تجربة";
// Add the text
imagettftext($im, 10, 0, 10, 20, $textcolor, $font, $text);


// set a red text color 
$textcolor = imagecolorallocate($im, 255, 0, 0);

// strrev doesn't seem to solve the problem
$text = strrev( $text );
// add the text
imagettftext($im, 10, 0, 30, 250, $textcolor, $font, $text);

imagefilledrectangle ($im, 0, 0, 1, 1, $bg);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
like image 480
Abu Romaïssae Avatar asked Jun 07 '14 00:06

Abu Romaïssae


2 Answers

Finally I've found a solution in some other forums, which is this tiny library word2uni and is worked perfectly, the whole thing is about converting the arabic letters into unicode symboles, practically, converting this:

$text = 'العربية'; 

to this:

$text = 'ﺔﻴﺑﺮﻌﻟﺍ';

and using, that library, which is making this conversion, so in my previous code it would work like that (after including the library):

// Create a 300*300 image
$im = imagecreate(300, 300);

// Yellow transparent background and blue text
$bg = imagecolorallocatealpha($im, 255, 255, 0, 45);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write an LTR string
imagestring($im, 5, 250, 100, 'test', $textcolor);

$font = 'DroidKufi-Regular.ttf'; // specify the fonts file
$text = "تجربة";
$text = word2uni( $text );
// Add the text
imagettftext($im, 10, 0, 10, 20, $textcolor, $font, $text);


// set a red text color 
$textcolor = imagecolorallocate($im, 255, 0, 0);

// strrev doesn't seem to solve the problem
$text = strrev( $text );
// add the text
imagettftext($im, 10, 0, 30, 250, $textcolor, $font, $text);

imagefilledrectangle ($im, 0, 0, 1, 1, $bg);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);

( the main thread )

like image 65
Abu Romaïssae Avatar answered Sep 22 '22 09:09

Abu Romaïssae


you can check this library

http://www.ar-php.org/Glyphs-example-php-arabic.html

here is an example how to use it

require('../I18N/Arabic.php');  
$Arabic = new I18N_Arabic('Glyphs'); 
$text = 'بسم الله الرحمن الرحيم';  
$text = $Arabic->utf8Glyphs($text);
like image 39
Salem Ahmed Avatar answered Sep 23 '22 09:09

Salem Ahmed