Search code examples
phpcairopango

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


I am working on a solution to automatically make an image of each word of a large document that contains a complex script (Khmer in UTF-8). I've found Pango and Cairo which can render Khmer correctly. I'm not much of a programmer, so I started with the PHP versions of Pango and Cairo. But I am not sure how to break up a string and produce an image for each word automatically. There are no "real" spaces between words, just the Unicode character U+0200B (a zero-width space).

Would someone be willing to help me?

Here's the code I am currently using that outputs the whole string:

<?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");
?>

Solution

  • I figured it out using 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;
    }
    ?>