how to align text in PIL pictures

Question:

I’m trying to output text to pictures with PIL. I was able to save the texts to png pictures but they are not aligned correctly.

Here is the code:

size = (2000, 500)
W, H = size
clear = PIL.Image.new(mode="RGB", size=size, color=(255, 255, 255))
draw = ImageDraw.Draw(clear)
font = ImageFont.truetype("ARIAL.TTF", size=20)
_, _, w, h = draw.textbbox((0, 0), formated_terminal_info, font=font)
draw.text(
    ((W - w) / 2, (H - h) / 2),
    formated_terminal_info,
    font=font,
    fill="black",
    align="left",
)
clear.save("test.png", "PNG")

I was able to format formated_terminal_info correctly in the terminal, and it looks like this:
formated_string_in_terminal

However, the PIL picture I got looks like this:
formated_string_in_PIL_picture

I’m wondering if I can get the text in the picture aligned correctly like they are displayed in the terminal.

Asked By: Johnzy

||

Answers:

You need to use a Monotype font, which is what terminals use to align each letter. With fonts like Arial, a lowercase L is less wide than an uppercase L, messing up the alignment.

Answered By: Daniel F
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.