PIL is a great package to create and edit images in Python. However, one problem it has is in calculating text size. So today I’m going to show you a short Python script used to draw properly centered text in images created with PIL.

The problem

Unfortunately, the textsize method of the drawing interface does not return the proper text size of a string.

For instance, with this sample code

img = Image.new("RGB", (width, height), color="white")
draw_interface = ImageDraw.Draw(img)
size_width, size_height = draw_interface.textsize("some string", font)

size_width and size_height would return incorrect values.

The solution

So, the solution is to use different calculations for the the text size. Following the solution posted in this Stack Overflow thread (with some changes), the function below is what I ended up with.

Text size calculation

Now let me try to explain the code.

Font metrics

#python #programming #design

How to properly calculate text size in PIL images
26.25 GEEK