当前位置: 动力学知识库 > 问答 > 编程问答 >

image processing - How to fit IMagick Canvas to font size in PHP?

问题描述:

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 examlpes I've found for PHP requires me to define the canvas size first.

Help!

网友答案:

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");
?>

分享给朋友:
您可能感兴趣的文章:
随机阅读: