Skip to content Skip to sidebar Skip to footer

How To Calculate Length Of String In Pixels For Specific Font And Size?

If the font, e.g. 'Times New Roman', and size, e.g. 12 pt, is known, how can the length of a string, e.g. 'Hello world' be calculated in pixels, maybe only approximately? I need th

Solution 1:

Based on comment from @Selcuk, I found an answer as:

from PIL import ImageFont
font = ImageFont.truetype('times.ttf', 12)
size = font.getsize('Hello world')
print(size)

which prints (x, y) size as:

(58, 11)

Here it is as a function:

from PIL import ImageFont

defget_pil_text_size(text, font_size, font_name):
    font = ImageFont.truetype(font_name, font_size)
    size = font.getsize(text)
    return size

get_pil_text_size('Hello world', 12, 'times.ttf')

Solution 2:

An alternative is to ask Windows as follows:

import ctypes

def GetTextDimensions(text, points, font):
    class SIZE(ctypes.Structure):
        _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]

    hdc = ctypes.windll.user32.GetDC(0)
    hfont = ctypes.windll.gdi32.CreateFontA(points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
    hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)

    size = SIZE(0, 0)
    ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))

    ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
    ctypes.windll.gdi32.DeleteObject(hfont)

    return (size.cx, size.cy)

print(GetTextDimensions("Hello world", 12, "Times New Roman"))
print(GetTextDimensions("Hello world", 12, "Arial"))

This would display:

(47, 12)
(45, 12)

Post a Comment for "How To Calculate Length Of String In Pixels For Specific Font And Size?"