Search code examples
phpfreetypeimagettftext

Underline text using imagettftext


My question is, how do I underline all the text in the image?

Code:

function createImage($text)
{
    $text .= "\n";
    $text = wordwrap($text, 40, "\n");
    $newlines = substr_count($text, "\n");
    if($newlines == 0)
    {
        $height = 30;
    }
    else
    {
        $height = 30*$newlines-$newlines*7;
    }
    putenv('GDFONTPATH=' . realpath('.'));
    header('Content-Type: image/png');

    $im = imagecreatetruecolor(315, $height);
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    $purple = imagecolorallocate($im, 97, 26, 139);
    imagefilledrectangle($im, 0, 0, 399, $height, $white);
    $font = 'arialbd.ttf';

    imagettftext($im, 11, 0, 10, 20, $purple, $font, $text);
    imagepng($im);
    imagedestroy($im);
}

createImage("Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow Stackoverflow ");

RESULT https://i.sstatic.net/Zdrx9.png

I want all the text to be underlined, I've found some solutions but they're only from left to right, not depending on words.


Solution

  • Use the Unicode underline combining character U+0332.

    You will need a loop to or clever array merge to modify the text,

    $e = explode(' ', $text);
    
    for($i=0;$i<count($e);$i++) {
      $e[$i] = implode('&#x0332;', str_split($e[$i]));
    }
    
    $text = implode(' ', $e);