Python 使用PIL创建多行文本

Python 使用PIL创建多行文本,python,python-imaging-library,Python,Python Imaging Library,所以我知道这里有一个类似的问题,但我的问题不同。因此,我有一个定义字体、图像、文本和最大文本宽度的代码: 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 = Imag

所以我知道这里有一个类似的问题,但我的问题不同。因此,我有一个定义字体、图像、文本和最大文本宽度的代码:

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
基本上,它应该返回这样的内容

lines = ['Message that is very long','and should exceed 250 pixels in','terms of width']
我试着自己做。。。但结果却是一团糟。我最初的计划是不断地从字符串中删除单词,然后将删除的单词放到另一个字符串中,但结果很糟糕。有人能帮忙吗

更新:v25所说的让我明白:

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')

您已将宽度设置为2500,但
文本长度仅为75个字符,因此在图像中仅产生一行。尝试使用
width=24
进行测试,结果列表应包含4项:

[“你好,我的名字是beep”,“boop,我正在开发”,“一个名为testing bot的机器人”,“123”]

您还可以避免在for循环中调用
draw.text
,因为它接受第二个参数的换行字符串

所以简单地说:

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")

当然,您还需要了解它是如何呈现背景图像的,并相应地调整背景图像的宽度。

如果您使用的是固定宽度字体,最好的解决方案是使用python的内置
textwrap
模块。@v25 check update
textwrap
需要字符数长度,而不是像素数