使用PHP将RTL(阿拉伯语)文本写入图像

Abu*_*sae 7 php image image-processing

我想生成一个带有一些文字的图像,LTR语言似乎工作得很好,但是在阿拉伯语中尝试它时,它简单地说不起作用,请看下面的截图,我在其中绘制3个文本字符串提出了文本代码

在此输入图像描述

这是我的测试代码(带一些注释):

// 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);
Run Code Online (Sandbox Code Playgroud)

Abu*_*sae 7

最后,我在其他一些论坛找到了解决方案,这是一个很小的库word2uni并且工作得很好,整个过程就是将阿拉伯字母转换为unicode symboles,实际上,转换为:

$text = '???????'; 
Run Code Online (Sandbox Code Playgroud)

对此:

$text = 'ﺔﻴﺑﺮﻌﻟﺍ';
Run Code Online (Sandbox Code Playgroud)

和使用,正在进行此转换的库,所以在我之前的代码中,它将像那样工作(包括库之后):

// 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);
Run Code Online (Sandbox Code Playgroud)

(主线程)

  • work2uni lib链接:https://github.com/sadi-techseed/wordofquran/tree/master/libs/word2uni (2认同)

Sal*_*med 5

你可以检查这个库

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

这是一个如何使用它的示例

require('../I18N/Arabic.php');  
$Arabic = new I18N_Arabic('Glyphs'); 
$text = '??? ???? ?????? ??????';  
$text = $Arabic->utf8Glyphs($text);
Run Code Online (Sandbox Code Playgroud)