Search code examples
phpimagegdtruetype

Wrap lines of text within image boundaries using gd


I am trying to write text from a db to images. The text some times contains lengthy lines so that it does't fit in one line on image.

As of now I am getting the output as: http://prntscr.com/29l582

This is the code for this:

$imageCreator = imagecreatefrompng($i+1 . ".png");
        $textColor = imagecolorallocate($imageCreator, 0, 0, 0);
        $textfromdb = $factformatted['fact'];
        $y = imagesy($imageCreator) - 228;
        $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
        $x = ceil(($imageWidth - $dimensions[4]) / 2);
        imagettftext($imageCreator, 20, 0, $x, $y, $textColor, $fontname, $textfromdb);
        imagepng($imageCreator, "./fact".$i.".png");

Can someone help me to make it work?


Solution

  • You can use the wordwrap function and the explode function to truncate the text in multiple arrays of string, then print them:

    $word = explode("\n", wordwrap ( "A funny string that I want to wrap", 10));
    

    You obtain this output:

     array(5) {
      [0]=>
      string(7) "A funny"
      [1]=>
      string(6) "string"
      [2]=>
      string(6) "that I"
      [3]=>
      string(7) "want to"
      [4]=>
      string(4) "wrap"
    }
    

    Than you can elaborate it (cutting the text, print each string on different lines, etc...).

    Example (printing on new lines):

    ...
    $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
    $y = imagesy($imageCreator) - 228;
    $text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
    $delta_y = 0;
    foreach($text as $line) {
        $delta_y =  $delta_y + $dimensions[3];
        imagettftext($imageCreator, 20, 0, 0, $y + $delta_y, $textColor, $fontname, $line);
    }
    ...
    

    To center both vertical and horizontal:

    ...
    $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
    $margin = 10;
    $text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
    $delta_y = 0;
    //Centering y
    $y = (imagesy($imageCreator) - (($dimensions[1] - $dimensions[7]) + $margin)*count($text)) / 2;
    
    foreach($text as $line) {
        $dimensions = imagettfbbox(20, 0, $fontname, $line);
        $delta_y =  $delta_y + ($dimensions[1] - $dimensions[7]) + $margin;
        //centering x:
        $x = imagesx($imageCreator) / 2 - ($dimensions[4] - $dimensions[6]) / 2;
    
        imagettftext($imageCreator, 20, 0, $x, $y + $delta_y, $textColor, $fontname, $line);
    }
    ...