PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 19, 2022

[FIXED] How can I wrap text using Imagick in PHP so that it is drawn as multiline text?

 September 19, 2022     annotate, imagick, php, text     No comments   

Issue

The Imagick library in PHP allows you to draw text on top of an image.

How can I tell Imagick to wrap the text based upon some bounded text box, so that the words appear as multiline text rather than a single line?


Solution

I have been using @Sarke's version successfully for a while, but I noticed there is an infinite loop if a word is longer than the $maxWidth. Here is a version that fixes the infinite loop:

function wordWrapAnnotation($image, $draw, $text, $maxWidth)
{   
    $text = trim($text);

    $words = preg_split('%\s%', $text, -1, PREG_SPLIT_NO_EMPTY);
    $lines = array();
    $i = 0;
    $lineHeight = 0;

    while (count($words) > 0)
    {   
        $metrics = $image->queryFontMetrics($draw, implode(' ', array_slice($words, 0, ++$i)));
        $lineHeight = max($metrics['textHeight'], $lineHeight);

        // check if we have found the word that exceeds the line width
        if ($metrics['textWidth'] > $maxWidth or count($words) < $i) 
        {   
            // handle case where a single word is longer than the allowed line width (just add this as a word on its own line?)
            if ($i == 1)
                $i++;

            $lines[] = implode(' ', array_slice($words, 0, --$i));
            $words = array_slice($words, $i);
            $i = 0;
        }   
    }   

    return array($lines, $lineHeight);
}


Answered By - John Langford
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing