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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With