PHP function to draw wrapped text

Here’s a PHP code snippet that draws text bounded by a textbox. You’ll need GD with TrueType support.

The snippet supports rotation, vertical and horizontal alignments, configurable line heights and leading, word wrap, character wrap, and text outlining.

The word wrapping is very greedy.

You can find the code snippet here:

Example usage:

$size = 14;
$angle = 34;
$left = 10;
$top = 40;
$color = imagecolorallocate($im, 255, 0, 0);
$fontfile = "arial.ttf";
$text = "Test";
$opt = array(
  'width' => 300,
  'line_height' => 15,
  'orientation' => array(ORIENTATION_TOP, ORIENTATION_LEFT),
  'align' => ALIGN_LEFT,
  'v_align' => VALIGN_TOP,
  'outlines' = array(
    array(5, imagecolorallocate($im, 0, 255, 0)),
    array(2, imagecolorallocate($im, 0, 0, 255)),
  // More options documented in the code
imagettftextboxopt($im, $size, $angle, $left, $top, $color, $fontfile, $text, $opt);
  • Amrish Prajapati

    Can i do text bold or italic with this ?

    • sk89q

      You can only bold or italicize the entire text block.

  • Anonymous

    die kann aber nicht von dir sein die ganze funktion da sind sehr viele fehler drin sogar auch im beispielcode der funktioniert noch nicht mal

  • golbarg


    I’ve started using your piece of code (works very well, thanks!), but I keep running into a small problem concerning text color. It seems like the parameter color generated using:
    $color = imagecolorallocate($image, $r, $g, $b);
    is not taken into account, and the rendered text looks like the average color from the entire $image file.

    Any ideas on how to solve this?

    • golbarg

      Never mind.

      I was using a GIF image and the palette was full, so it could not process the imagecolorallocate correctly.

      Converted it to JPG and worked like a charm.

  • Darknight

    The link for the code for imagettftextboxopt doesn’t work.

    Does it will work even with php 5.3?

    • sk89q

      I will post it later tonight.

      It should work with PHP 5.3. It isn’t really exotic.

      • Rick

        Looks like a great function!
        I’ll really want to try it.

        Could you post me it too?

        • sk89q

          Should be up now.

  • http://- Carlos

    Is there any way of justifying the text both left and right sides? I mean, re-distribute the spaces between words so it coual be double justify.


  • xcanner

    Is the code still available?