python - 使用 PIL 创建多行文本

标签 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 = 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')

https://prnt.sc/uk6wp5

最佳答案

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

['你好,我的名字是 beep', 'boop,我正在开发', '一个名为测试机器人的机器人', '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 - 使用 PIL 创建多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63971442/

相关文章:

python - 如何使用 python-apt API 安装包

python - 使用Python去噪图像算法

python - StringIO 无法识别图像文件错误

python - 禁用标准。和 Python 沙箱实现中的文件 I/O

python - 使用 PIL 模块的 UnicodeDecodeError

python - 如何打印出一张图片的平均像素?

python - 内存中图像到 Zip 文件

python - 如何让 matplotlib 和 latex 一起工作?

python - 了解 Python 导入和循环依赖的行为

python - Tornado 中的电子商务(非阻塞)VS Flask (WSGI)