Produci un'immagine per ogni parola piuttosto che per l'intera stringa in PHP usando Pango e Cairo
Domanda
Sto lavorando a una soluzione per creare automaticamente un'immagine di ogni parola di un documento di grandi dimensioni che contiene uno script complesso (Khmer in UTF-8).Ho trovato Pango e Cairo che possono rendere Khmer correttamente.Non sono un gran programmatore, quindi ho iniziato con le versioni PHP di Pango e Cairo.Ma non sono sicuro di come spezzare una stringa e produrre automaticamente un'immagine per ogni parola.Non ci sono spazi "reali" tra le parole, solo il carattere Unicode U + 0200B (uno spazio di larghezza zero).
Qualcuno sarebbe disposto ad aiutarmi?
Ecco il codice che sto utilizzando attualmente che restituisce l'intera stringa:
<?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");
?>
Soluzione
L'ho capito usando 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;
}
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow