Search code examples
graphicsfontsimagemagick-convertappearance

Programmatically determine text size in ImageMagick


I know one way to determine the text of a string, in a particular font and font size, without line breaks: use convert to create a new image containing only that string, and then examine the created image for its dimensions. In other words, I will be extremely surprised if this is the best way.

What is the preferred way to calculate what the dimensions of a one-line string/font/font size?


Solution

  • The best guide to this is Anthony Thyssen's excellent ImageMagick Usage pages, specifically here and then search on that page for the word "Metrics".

    Here is an example command and output:

    convert -debug annotate  xc: -pointsize 36 -annotate 0 'Get my metrics' null: 2>&1 | grep Metrics: | fmt -w80
    
    Metrics: text: Get my metrics; width: 241; height: 41; ascent: 33; descent:
    -8; max advance: 72; bounds: 1.10938,-7  16.6094,19; origin: 242,0; pixels per
    em: 36,36; underline position: -4.5625; underline thickness: 2.34375