How to calculate length of string in pixels for specific font and size? How to calculate length of string in pixels for specific font and size? python-3.x python-3.x

How to calculate length of string in pixels for specific font and size?


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

from PIL import ImageFontfont = 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 ImageFontdef get_pil_text_size(text, font_size, font_name):    font = ImageFont.truetype(font_name, font_size)    size = font.getsize(text)    return sizeget_pil_text_size('Hello world', 12, 'times.ttf')


An alternative is to ask Windows as follows:

import ctypesdef 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)