Asaf Strilitz
Asaf Strilitz

Reputation: 191

How to get data from font on python

on js we used to get data via https://github.com/dy/font-measure

ascender: 0.95
capHeight: 0.89
height: (fontData.ascender - fontData.descender) * -1;//1.4
median: 0.47

but have no idea how to get those value on python tried

        from PIL import ImageFont

        text = 'sphinx'
        H = 100
        font = ImageFont.truetype(font, H, encoding='utf-8')
        ascent, descent = font.getmetrics()
        (width, baseline), (offset_x, offset_y) = font.font.getsize(text)

but I can't get the numbers quite right and am not sure what is what. any help on this will be appreciated.

images: js one : js image python one -i think? enter image description here

Upvotes: 1

Views: 947

Answers (1)

Nulano
Nulano

Reputation: 1353

You can get the bounding box with font.getbbox("text", anchor="ls") (the anchor indicates you are interested in coordinates relative to the left-baseline point) and the advance length with font.getlength("text"). You already have the maximum ascent and descent values from font.getmetrics(). The line height is font.font.height. The cap height and x height are not available via Pillow, but you could try -font.getbbox("A", anchor="ls")[1] for the cap height and -font.getbbox("x", anchor="ls")[1] for the x height.

You might be interested in reading the text anchor documentation in detail.

Upvotes: 0

Related Questions