Search code examples
phpimagick

PHP Imagick how to best fit text annotation


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;

Solution

  • 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.