As of Pillow v9.2.0
, .getsize
is deprecated, and will be removed in Pillow v10
on 2023-07-01. Instead, use getbbox
or getlength
.
Tested in python 3.11.2
, pillow v9.4.0
from PIL import ImageFont
font = ImageFont.truetype('times.ttf', 12)
left, top, right, bottom = font.getbbox('Hello world')
width = font.getlength('Hello world')
print(f'left: {left}, top: {top}, right: {right}, bottom: {bottom}, width: {width}')
[out]:
left: 0, top: 2, right: 58, bottom: 11, width: 57.0
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')