image-processingimagemagick

Get geometry of text on an image


I'd like to draw a text onto an image in a way like this:

convert -quality 100 -font Oswald-Regular -pointsize 515 -fill black -draw "text 1339.0,1099 'some text'" /tmp/ascript.png /tmp/ascript.png

and I need to know the dimensions of the text with the above parameters (size, font, text). How can I get that?

I tried something like this:

convert -size 5000x1500 xc:lightblue -font Oswald-Regular -pointsize 515 -fill none -undercolor white -annotate +20+100 'some text' -trim  info:

but it's giving false result:

xc:lightblue XC 1834x250 5000x1500+19+0 16-bit sRGB 0.010u 0:00.000

.

What is the proper way (or a working way) to get the dimension of a drawn image based on this 3 parameters (font, size, text)?

I'm not strictly binded to ImageMagick, it can be any command line tool for the Linux shell, however, the text will be drawn by convert.


Solution

  • There are a couple simple ways to get the dimensions using ImageMagick with commands like this...

    convert -size 5000x1500 xc:lightblue -font Oswald-Regular -pointsize 515 \
        -fill none -undercolor white -annotate +20+100 'some text' \
        -format "%[@]\n" info:
    

    That uses the FX escape "%@" as the formatting string for the "info:" output. It will show IM's calculation of the after-trim width, height, horizontal offset, and vertical offset like "WxH+X+Y".

    This similar command just gives the width and height of the trimmed text...

    convert -size 5000x1500 xc:lightblue -font Oswald-Regular -pointsize 515 \
        -fill none -undercolor white -annotate +20+100 'some text' \
        -trim +repage -format "%[w]x%[h]\n" info:
    

    That will trim the text, reset the paging geometry with "+repage", then output a string showing "WxH".

    ––– Edited to Add –––

    I tried your image with_text.png with these commands. The output immediately follows each command...

    convert with_text.png -format "%[@]\n" info:
    1807x389+512+115
    
    convert with_text.png -trim +repage -format "%[w]x%[h]\n" info:
    1807x389
    

    Those were tested with IMv6.8.9-9 on ubuntu bash on Windows 10. If you use that actual image and those commands, I'm not sure why you would get different results.