pergunt0
pergunt0

Reputation: 93

How to add text-align justify in Pillow?

I have a code that I use wrap text, but I would like to add text-align: justify in order to fill whole image. How do I do this?

from PIL import Image, ImageDraw, ImageFont
import textwrap

astr = 'Python '
para = textwrap.wrap(astr*100, width=15)

MAX_W, MAX_H = 200, 200
im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('arial.ttf', 18)

current_h, pad = 0, 0
for line in para:
    w, h = draw.textsize(line, font=font)
    draw.text(((MAX_W - 1.7*w) / 2, current_h), line, font=font)
    current_h += h + pad

im

Output:

enter image description here

Upvotes: 1

Views: 690

Answers (1)

RoseGod
RoseGod

Reputation: 1234

I don't believe there is an option like text-align: justify in pillow but you can do this by hard coding what you need.

code:

from PIL import Image, ImageDraw, ImageFont
import textwrap


im = Image.new('RGB', (200, 200), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)


astr = 'Python '
font = ImageFont.truetype('arial.ttf', 15)
num_row = 4


draw.text((0,0), astr * num_row, font=font)
draw.text((0,30), astr * num_row, font=font)
draw.text((0,60), astr * num_row, font=font)
draw.text((0,90), astr * num_row, font=font)
draw.text((0,120), astr * num_row, font=font)
draw.text((0,150), astr * num_row, font=font)
draw.text((0,180), astr * num_row, font=font)
im

Output:

Output

Note - you can change the font size and how many times python appears in each line to make it fit for your wanted image.

Upvotes: 1

Related Questions