Need to draw autofitted text that is..

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
kennyken747
Posts: 1
Joined: 2012-12-28T13:26:00-07:00
Authentication code: 6789

Need to draw autofitted text that is..

Post by kennyken747 »

Hi all. I need to draw text over background images. The width of the text needs to automatically fit in the width of the image as wide as possible while still having a small left/right margin.

I'm halfway there using labels, but I'm running into some problems with positioning. I need the text to be horizontally centered (left/right margin should be equal), but I need it to translate up or down along the y axis depending on my offset. So I can't use -gravity center.

Any help would be greatly appreciated.


Here is what I have now:
For example, with a 300x300 image

convert -background none -size 300x300 -fill 'black' label:"Test" test_label.png

convert bg.png -draw 'image over 6,60 0,0 "test_label.png"' out.png

The x, y are actually being determined programmatically by a Python script. I'm using the width of the image * 0.02 to determine X. This fails to center the text for most cases, and was only sufficient for the test case where the label is "Test"

Is there some way I can logically chain the commands? Say, start off with -gravity center and then translate the label up or down from there?
Again, any help would be greatly appreciated.
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Need to draw autofitted text that is..

Post by snibgo »

There are loads of ways of doing this. "-gravity South" may be useful, as may the fact that

Code: Select all

-label:"  Test  "
will give padding on each side of the text (by shrinking the font size).
snibgo's IM pages: im.snibgo.com
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Need to draw autofitted text that is..

Post by fmw42 »

Create a label: image with transparent background and -gravity center to the desired width (only) and no pointsize. If desired use -trim and also if desired -bordercolor none -border X to pad. Then composite the image over some other image using -gravity north to center it and then -geometry to shift it down (or sideways).

Use snibgo's concept of padding the text on the left and right with a space to ensure that it fits the width, if needed.

see
http://www.imagemagick.org/Usage/text/#label_bestfit
and
http://www.imagemagick.org/Usage/layers/#convert
Post Reply