使用Pango和Cairo在PHP中为每个单词而不是整个字符串输出图像


Output an Image for Each Word Rather than the Whole String in PHP Using Pango and Cairo

我正在研究一种解决方案,可以自动为包含复杂脚本(UTF-8中的高棉语)的大型文档的每个单词制作图像。我找到了能正确翻译高棉语的Pango和Cairo。我不是一个很好的程序员,所以我从Pango和Cairo的PHP版本开始。但是我不确定如何分解字符串并自动为每个单词生成图像。单词之间没有"真正的"空格,只有Unicode字符U+0200B(零宽度空格)。

有人愿意帮助我吗?

下面是我当前使用的输出整个字符串的代码:

<?php
header("Content-Type: image/png");
/* Make a 300x300px image surface */
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 300);
$c = new CairoContext($s);
/* Set the background to white */
$c->setSourceRGB(1, 1, 1);
$c->paint();
/* Let's draw using black 'ink' */
$c->setSourceRGB(0, 0, 0);
/* Make a Pango layout, set the font, then set the layout size */
$l = new PangoLayout($c);
$desc = new PangoFontDescription("KhmerOS Regular 28");
$l->setFontDescription($desc);
$l->setWidth(250 * PANGO_SCALE);
/* Here is the text */
$l->setMarkup("កាល​ដើម​ដំបូង​ឡើយ ព្រះ​បាន​បង្កើត​ផ្ទៃ​មេឃ និង​ផែនដី។");
/* Draw the layout on the surface */
$l->showLayout($c);
/* Output the PNG to the browser */
$s->writeToPng("php://output");
?>

我使用foreach:

<?php
//header("Content-Type: image/png");
$str = "កាល​ដើម​ដំបូង​ឡើយ ព្រះ​បាន​បង្កើត​ផ្ទៃ​មេឃ និង​ផែនដី។";
//$words = explode('​', $str);
$words = preg_split('/ |​/', $str);
$i=1;
foreach($words as $word) {
/* Make a 300x300px image surface */
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 300);
$c = new CairoContext($s);
/* Set the background to white */
$c->setSourceRGB(1, 1, 1);
$c->paint();
/* Let's draw using black 'ink' */
$c->setSourceRGB(0, 0, 0);
/* Make a Pango layout, set the font, then set the layout size */
$l = new PangoLayout($c);
$desc = new PangoFontDescription("KhmerOS Regular 28");
$l->setFontDescription($desc);
$l->setWidth(250 * PANGO_SCALE);

/* Here, we use Pango markup to make part of the text bold */

$i++;
$l->setMarkup($word);
/* Draw the layout on the surface */
$l->showLayout($c);
/* Output the PNG to the browser */
//$s->writeToPng("php://output");
$s->writeToPng(dirname(__FILE__) . '/test'.$i.'.png');
echo $img = "<img src='"test".$i.".png'">";
echo $i;
}
?>