I want to create a simple image which only contains 1 line of text. Similar to this:
http://www.imagemagick.org/Usage/text/#label
However, I'd like to keep it within php's Imagick. I know the font size, and I want the canvas size to fit to the font size, like it does in the example. Unfortunately, I don't see a way to do this with Imagick in PHP. All examples I've found for PHP requires me to define the canvas size first.
You can do something like this, by querying the font metrics, but there may be a better way that I don't know of....
#!/usr/local/bin/php -f
<?php
$image = new Imagick();
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
$draw->setFontSize(24);
$text="Hello, I am a lovely label";
// Set typeface
$draw->setFont('Impact');
// Calculate size
$metrics = $image->queryFontMetrics($draw,$text,FALSE);
$w=$metrics['textWidth'];
$h=$metrics['textHeight'];
$y=$metrics['ascender'];
$image->newImage($w,$h,"steelblue","png");
$image->annotateImage($draw,0,$y,0,$text);
$image->writeImage("result.png");
?>