Basic word wrapping with Imagick

The following is a simple greedy word-wrapping algorithm for ImageMagick in PHP.

Released under public domain.

$words = explode(" ", $msg);
$lines = array();
$current_line = "";
foreach ($words as $word) {
  if ($current_line == "") {
    $test = $word;
  } else {
    $test = "$current_line $word";
  }
  $metrics = $image->queryFontMetrics($draw, $test);
  if ($metrics['textWidth'] > $max_width) {
    if ($current_line == "") {
      $lines[] = $test;
      $current_line = "";
    } else {
      $lines[] = $current_line;
      $current_line = $word;
    }
  } else {
    $current_line = $test;
  }
}
if ($current_line != "") {
  $lines[] = $current_line;
}
$msg = implode("\n", $lines);

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.

Continue reading