walid
walid

Reputation: 107

Creating a multiline text using PIL

So I know there is a question somewhat similar to this on here, however mine is different. So I have this code that defines the font, image, text, and maximum text width:

from PIL import Image, ImageFont
texts = ['This is a test', 'Message that is very long and should exceed 250 pixels in terms of width']
bg = Image.open(f"data/background.png")
font = ImageFont.truetype(f"data/minecraft-font.ttf", 16)
text_width = font.getsize(texts[1])[0]
if text_width > 250:
# return a list that has the lines

basically it should return something like this

lines = ['Message that is very long','and should exceed 250 pixels in','terms of width']

I tried to do it myself... but it turned out to be a mess. My original plan was to continuously remove words from the string and put the removed words in another string but that turned out horrible. Can anyone help?

UPDATE: What v25 said gets me this:

import requests
from PIL import ImageFont, Image, ImageOps, ImageDraw
import textwrap
offset = margin = 60
bg = Image.open('data/background.png').resize((1000,1000))
font = ImageFont.truetype(f"data/minecraft-font.ttf", 16)
text = 'Hello my name is beep boop and i am working on a bot called testing bot 123'
draw = ImageDraw.Draw(bg)
for line in textwrap.wrap(text, width=2500):
    draw.text((offset,margin), line, font=font, fill="#aa0000")
    offset += font.getsize(line)[1]
bg.save('text.png')

https://prnt.sc/uk6wp5

Upvotes: 2

Views: 2739

Answers (1)

v25
v25

Reputation: 7621

You've set the width to 2500, but text is only 75 characters long, hence this only producing one line in the image. Try testing with width=24 and the resulting list should contain 4 items:

['Hello my name is beep', 'boop and i am working on', 'a bot called testing bot', '123']

Also you could avoid calling draw.text inside a for loop, as it accepts a string with newlines for the second argument.

So simply something like:

text = 'Hello my name is beep boop and i am working on a bot called testing bot 123'
textwrapped = textwrap.wrap(text, width=24)
draw.text((offset,margin), '\n'.join(textwarpped), font=font, fill="#aa0000")

Of course you'd then need to see how this renders and tweak the width accordingly for your background image.

Upvotes: 2

Related Questions