Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to align text in PIL pictures

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading