Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 this to do some manual right alignment of text shown in an Windows application, so I need to adjust the number spaces to get the alignment.

like image 986
EquipDev Avatar asked Mar 03 '16 12:03

EquipDev


1 Answers

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')
like image 59
EquipDev Avatar answered Oct 08 '22 14:10

EquipDev