PHP Imagick how text annotation works best

I am adding annotation text to newPseudoImage, which works fine, but I would like the text scale to fit the image size.

Any ideas how I can do this?

$im = new Imagick(); $draw = new ImagickDraw(); $draw->setFillColor($color); $draw->setFont($font); $draw->setFontSize(($width, $height) / 100) * 15); $draw->setGravity(Imagick::GRAVITY_CENTER); $im->newPseudoImage($width, $height, "canvas:{$bg}"); $im->annotateImage($draw, 0, 0, 0, $text); $draw->clear(); $draw->destroy(); $im->setImageFormat('gif'); header("Content-Type: image/gif"); echo $im; 
+4
source share
3 answers

I think you could use the imageftbbox function to help you.

This will give you a bounding box for the text string with the given font, size and angle ttf.

You can create a loop to increase or decrease the font size until the text matches the image correctly.

 <?php $bbox = imageftbbox(12, 0, 'Arial.ttf', 'This is a test'); $width_of_text = $bbox[2] - $bbox[0]; 

You can look at $width_of_text and adjust the font size until the font is scaled to your liking. Keep in mind that as the font increases, the width and height will increase.

Depending on what you are trying to scale, this may help.

+8
source

I faced the same problem, and although I have not tried it yet, since I am far from my car, I am going to give it away.

Using the query metrics function in the class, I can get the calculated width of the text, and then compare it with the specified width of its container. I will make adjustments to the font size and repeat until it gets closer. You could get it pretty accurately this way, but don't forget about possible performance issues if you have multiple text elements in the image.

On the other hand, if you were not interested in styling the text the way you could use a headline.

+1
source

This is a bit naive solution (I could use binary search to find the correct font size), but it works for me.

In my example, I want to put text in a field on an image, so I calculate the correct font size using imageftbbox.

 $size = $MAX_FONT_SIZE; while (true){ $bbox = imageftbbox($size, 0, $font, $text ); $width_of_text = $bbox[2] - $bbox[0]; if ($width_of_text > $MAX_TEXT_WIDTH) { $size -= 1; } else { break; } } $height_of_text = ($bbox[3] - $bbox[1]); $draw->setFontSize( $size ); $image->annotateImage($draw, $TEXT_WIDTH_CENTER - $width_of_text/2, $TEXT_HEIGHT_CENTER - $height_of_text/2, 0, $text); 
-1
source

All Articles