Imagick is a great extension for PHP that allows you to create and manipulate images. It is much better than GD.
I wanted to draw some word wrapped text, but the unfortunate thing with Imagick is that you must use “caption:” and give up all control over the formatting of the text. If you want text formatting, you have to use Imagick’s annotation method, but then you don’t have word wrapping. So the solution is to implement our own word wrapping algorithm.
The one here is a fairly simple greedy word wrapping algorithm, but it should be somewhere to start off from. The idea is that we have a running string ($current_line) that contains enough words to fit within a $max_width. We go through each $word and make a new test string $test, containing $current_line and the new word. If $test is too wide, then we add $current_line (without the newly added word) to a $lines array, set $current_line to the new $word and repeat the process. If $test is still under the width, we continue adding on more words.
The code is:
$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);
I'm on Twitter!
Too bad Imagick’s annotateImage method doesn’t support word wrapping. I figured it would, since the queryFontMetrics method supports a multiline parameter. What good is this parameter if it can’t be used with annotating?!?