python的PIL绘制多行文本的图像。
16lz
2021-01-22
I try to add text at the bottom of image and actually I've done it, but in case of my text is longer then image width it is cut from both sides, to simplify I would like text to be in multiple lines if it is longer than image width. Here is my code:
我试着在图像底部添加文本,实际上我已经做过了,但是如果我的文本更长,那么图像宽度从两边都剪下来,为了简化,如果文本长度大于图像宽度,我希望文本是多行的。这是我的代码:
FOREGROUND = (255, 255, 255)
WIDTH = 375
HEIGHT = 50
TEXT = 'Chyba najwyższy czas zadać to pytanie na śniadanie \n Chyba najwyższy czas zadać to pytanie na śniadanie'
font_path = '/Library/Fonts/Arial.ttf'
font = ImageFont.truetype(font_path, 14, encoding='unic')
text = TEXT.decode('utf-8')
(width, height) = font.getsize(text)
x = Image.open('media/converty/image.png')
y = ImageOps.expand(x,border=2,fill='white')
y = ImageOps.expand(y,border=30,fill='black')
w, h = y.size
bg = Image.new('RGBA', (w, 1000), "#000000")
W, H = bg.size
xo, yo = (W-w)/2, (H-h)/2
bg.paste(y, (xo, 0, xo+w, h))
draw = ImageDraw.Draw(bg)
draw.text(((w - width)/2, w), text, font=font, fill=FOREGROUND)
bg.show()
bg.save('media/converty/test.png')
5 个解决方案
#1
34
You could use textwrap.wrap
to break text
into a list of strings, each at most width
characters long:
您可以使用textwrap。将文本转换成字符串列表,每个字符串的宽度都是最长的:
import textwrap
lines = textwrap.wrap(text, width=40)
y_text = h
for line in lines:
width, height = font.getsize(line)
draw.text(((w - width) / 2, y_text), line, font=font, fill=FOREGROUND)
y_text += height
更多相关文章
- linux vim下如何让类似txt的文本,呈现出某种语言的高亮形式?
- 文本文件到字符串数组?
- 文本处理小工具SED用法
- 个人网站对xss跨站脚本攻击(重点是富文本编辑器情况)和sql注入攻击
- MySql WorkBench“执行查询到文本输出”选项未显示完整结果
- android studio中的文本替换
- android在onCreate()方法中获取View的宽度与高度的方法实战
- Android ListView快速滚动段:段文本太长
- 为什么我们应该将XMPP而不是JSON用于简单(仅文本)消息传递应用程序