ImageMagick: how to draw two strings with different size over image?

你。 提交于 2019-12-10 21:18:08

问题


I want to draw a rectangle with two strings in it. I want the first string to be 15pt size (its a number), second to be 10pt size (the label). It's easy to draw single string with one size to the rectangle, I do it like this:

$image = new Imagick('someimage.png');
$draw = new ImagickDraw;
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->setfont(__DIR__ . DS . 'TREBUCBD.TTF');
$draw->setfontsize(15);
$draw->annotation(0, 0, '50 points');
$image->drawImage($draw);

The idea here is to have "50" in "50 points" to be big.

I tried to do a $draw->push() to push the current settings to the stack then set the font size and annotation again but then the two strings overlap. I've been trying to do this for hours. Any help is very appreciated!

The above implementation is in PHP but probably I will manage to do it even by example that shows it with command line ImageMagick usage.

edit: I've started a bounty that I will award for a solution implemented in PHP.


回答1:


Add enough space before "points" and after the "50" so you align them nicely:

<?php
$image = new Imagick('test.png');
$draw = new ImagickDraw;
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->setfontsize(30);
$draw->annotation(0, 0, '50         ');
$image->drawImage($draw);

$draw = new ImagickDraw;
$draw->setGravity(Imagick::GRAVITY_CENTER);
$draw->setfontsize(15);
$draw->annotation(0, 0, '      points');
$image->drawImage($draw);

file_put_contents('test.png', $image->getImageBlob());
?>



回答2:


You can use +append option to make two different text labels joined horizontally (-append - vertically):

convert -background grey -pointsize 15 -fill black label:abc \
        -pointsize 10 -fill red label:cdefgh -gravity South +append test.png

This code actually produces two images sized exactly to fit font (since there's no explicit size specified), and then this two images are horizontally appended together:

Once again: the size of this image is calculated automatically to fit your labels. You can use Imagick::labelImage and Imagick::appendImages functions to achieve this. (To make image without background, you can specify -backround transparent, e.g. via Imagick::setBackgroundColor)

After that, resulting image with labels can be composed with anything you want.



来源:https://stackoverflow.com/questions/7221686/imagemagick-how-to-draw-two-strings-with-different-size-over-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!