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 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

def get_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')

Leave a Comment