2016-03-03 46 views
1

我想創建一個僅包含1行文本的簡單圖像。與此相似:如何在IMagick Canvas中使用PHP字體大小?

http://www.imagemagick.org/Usage/text/#label

不過,我想保持它PHP的Imagick內。我知道字體大小,並且我希望畫布大小適合字體大小,就像它在示例中一樣。不幸的是,我沒有看到用PHP中的Imagick做到這一點。我爲PHP找到的所有示例都要求我先定義畫布大小。

幫助!

+0

使用了非常大的畫一個然後使用trimImage() - 示例是:http://phpimagick.com/Tutorial/imageGeometryReset的一部分 - 但是,queryFontMetrics也是一個不錯的選擇。 – Danack

回答

1

你可以做這樣的事情,通過查詢字體規格,但也有可能是一個更好的辦法,我不知道....

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

enter image description here