Home > Net >  Using Pillow to center multi-line text without it going off the image
Using Pillow to center multi-line text without it going off the image

Time:10-17

For context, I am trying to make a 'sigma-male' meme generator. The idea is I can feed in a load of pre-defined 'sigma-male' jokes/quotes and overaly it on an image of a 'sigma-male'. The format of these pictures should be that in the center of the image there will be a line saying 'Sigma-Male Rule #X' and underneath there would be some bad life advice e.g. 'Don't be part of the problem, be the whole problem'. Here is the picture I am starting with (note that for my purposes all images are the same size, 1080x1080. So issues of variable image size shouldn't be a problem):

enter image description here


BTW:

You can use getlength() and getbbox() also to test text with different font size to get text which fit in one line.

CodePudding user response:

I guess im doing more or less the same as furas The difference is that I compare line length. For this to work you have to split at \n as the length is not calculated on wrapped text.

So you split the wraps, compare the length, select the longest line, increase font size until it matches the image size. Thats it.

from PIL import Image, ImageDraw, ImageFont

my_image = Image.open("image.jpg")
font = ImageFont.truetype('ANTQUAB.TTF', 10)
title_text = "Sigma Male Rule #1"
content_text = 'Don\'t be part of the problem,\nbe the whole problem'
font_size = 10

while True:
    title_size = font.getlength(title_text)
    content_size = font.getlength(content_text)
    text_length = 0
    for line in content_text.split('\n'):
        if len(line) > text_length:
            text_length = len(line)
            content_size = font.getlength(line)

    size = title_size if title_size > content_size else content_size
    if size >= 1060:
        break
    font_size  = 1
    font = ImageFont.truetype('ANTQUAB.TTF', font_size)

image_editable = ImageDraw.Draw(my_image)
image_editable.text((200, 400), title_text, (255, 255, 255), font=font, stroke_width=2, stroke_fill='black',
                    align='center')
image_editable.text((0, 500), content_text, (255, 255, 255), align='center', font=font, stroke_width=2,
                    stroke_fill='black')

my_image.save("result.jpg")
  • Related