Center-/middle-align text with PIL?

How would I center-align (and middle-vertical-align) text when using PIL?

Answer

Use Draw.textsize method to calculate text size and re-calculate position accordingly.

Here is an example:

from PIL import Image, ImageDraw

W, H = (300,200)
msg = "hello"

im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
w, h = draw.textsize(msg)
draw.text(((W-w)/2,(H-h)/2), msg, fill="black")

im.save("hello.png", "PNG")

and the result:

image with centered text

If your fontsize is different, include the font like this:

myFont = ImageFont.truetype("my-font.ttf", 16)
draw.textsize(msg, font=myFont)