ImageMagick函数queryFontMetrics的结果不准确

时间:2012-06-27 23:02:33

标签: imagemagick

Imagick :: queryFontMetrics似乎不起作用。当我使用queryFontMetrics提供的指标来调整图像大小时,某些字体仍然被切断。有什么想法吗?

这是我的代码:

if (!file_exists($cache['dirname'].'/'.$cache['basename'])) {

try {
    $draw = new ImagickDraw();
    $draw->setFont($font_path['dirname'].'/'.$font_path['basename']);
    $draw->setFontSize($size);
    $draw->setGravity(Imagick::GRAVITY_CENTER);
    $draw->setFillColor($color);

    $canvas = new Imagick();

    $metrics = $canvas->queryFontMetrics($draw, $text);

    $canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png");
    $canvas->annotateImage($draw, 0, 0, 0, $text);

    $canvas->setImageFormat('PNG');
    mkdir($cache['dirname'], 0777, true);
    $canvas->writeImage($cache['dirname'].'/'.$cache['basename']);

    header("Content-Type: image/png");
    echo $canvas;

    $canvas->clear();
    $canvas->destroy();

    $draw->clear();
    $draw->destroy();

} catch(Exception $e) {
    // Output an error message
    echo 'Error: ',  $e->getMessage(), "";
}

} else {
    // Output the image
    $canvas = new Imagick($cache['dirname'].'/'.$cache['basename']);
    header("Content-Type: image/png");
    echo $canvas;
}

1 个答案:

答案 0 :(得分:2)

好吧,看起来我自己会回答这个问题。经过相当多的研究,我发现从字体本身获取正确的指标基本上是不可能的。这是因为每个字体设计者都可能以不同方式定义指标。最好的方法是简单地使图像大于必要(确保不发生剪裁),然后使用trim命令:http://www.php.net/manual/en/imagick.trimimage.php