Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Imagick how to best fit text annotation

Tags:

php

imagick

I'm adding annotation text to a newPseudoImage which works fine but I'd like to make the text scale to fit the image size.

Any ideas how I might 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;
like image 220
DrKHunter Avatar asked Dec 21 '22 08:12

DrKHunter


2 Answers

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

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

You could create a loop to increase or decrease the font size as long as the text is not fitting the image properly.

<?php

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

You could look at the $width_of_text and adjust the font size as long as the font isn't scaled to your liking. Keep in mind, as you increase the font, the width and height will grow.

Depending on what you are trying to scale it to that may help.

like image 72
drew010 Avatar answered Dec 24 '22 01:12

drew010


I'm facing the same issue and although I've not tried this yet as I'm away from my machine, I'm going to give this a go.

Using the query font metrics function of the class I will be able to get the calculated width of the text and then compare it with the specified width of its container. I'll make adjustments to the font size and repeat until its near enough. You could get it quite accurate this way but bare in mind possible performance issues if you have multiple text items in the image.

On the other hand, if you weren't concerned about styling the text as much you could use caption.

like image 37
digout Avatar answered Dec 24 '22 02:12

digout