Calculating the correct font size based on an amount of pixels

Discuss digital image processing techniques and algorithms. We encourage its application to ImageMagick but you can discuss any software solutions here.
Post Reply
jensen31
Posts: 8
Joined: 2016-01-01T16:15:43-07:00
Authentication code: 1151

Calculating the correct font size based on an amount of pixels

Post by jensen31 »

Hello Community,

is there a way to calculate the font size depending on a given amount of pixels?

Example: I draw text on 5 different images. The words drawen have different amount of characters. Some 3 long, some 12.
Right now I have a variable $FONTSIZE where I substract the amount of characters*10. Simply means: Longer words get a smaller $FONTSIZE.
Problem: This works with words till 9 character, but not for 12 or even longer. In total longer words get too small.

So I asked myself, is there a way to tell ImageMagick an amout of pixels like 300 and is calculates the best fontsize like: Ok 300 pixel, word to draw 4 letters, fitting fontsize = 130

Thank you very much and have a nice day.
Jens
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Calculating the correct font size based on an amount of pixels

Post by snibgo »

IM can calculate a best-fit pointsize. See http://www.imagemagick.org/Usage/text/#caption_bestfit . So you can create an image for the text, then composite that over another image if you want.
snibgo's IM pages: im.snibgo.com
jensen31
Posts: 8
Joined: 2016-01-01T16:15:43-07:00
Authentication code: 1151

Re: Calculating the correct font size based on an amount of pixels

Post by jensen31 »

snibgo wrote: 2019-01-28T07:03:18-07:00 IM can calculate a best-fit pointsize. See http://www.imagemagick.org/Usage/text/#caption_bestfit . So you can create an image for the text, then composite that over another image if you want.
This works perfect! Thank you so much.
I only have one question... When I copy this into my putty connection it works without error. But when I write it into a script file like test.sh (made it executable) then I get errors.

Code
#!/bin/bash
convert -background red -font Helvetica -gravity center -size 617x176 \
caption:'Big Test' \
"/skripte/imgRender/test/caption_filled.gif"


Error (when in script)
: File or directory not found

How can that be? Why working in command line but not in script? I guess it is a greenhorn thing...

Its not the first time I have this problem. Always when multi line is doesnt work... Where is my mistake?
Thank you!
jens
Post Reply