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

更多相关文章

  1. linux vim下如何让类似txt的文本,呈现出某种语言的高亮形式?
  2. 文本文件到字符串数组?
  3. 文本处理小工具SED用法
  4. 个人网站对xss跨站脚本攻击(重点是富文本编辑器情况)和sql注入攻击
  5. MySql WorkBench“执行查询到文本输出”选项未显示完整结果
  6. android studio中的文本替换
  7. android在onCreate()方法中获取View的宽度与高度的方法实战
  8. Android ListView快速滚动段:段文本太长
  9. 为什么我们应该将XMPP而不是JSON用于简单(仅文本)消息传递应用程序

随机推荐

  1. 什么是asp.net core?介绍Asp.Net Core的优
  2. asp.net core实例详解三(新建项目)
  3. vs 中引用的问题--出现小叹号
  4. 推荐10款常用的获取本机ip用法,欢迎下载!
  5. asp.net core实例详解二(环境设置)
  6. 有关浮点数类型的文章推荐3篇
  7. C# 一些面试试题的实例教程
  8. ASP.NET Core实例详解一
  9. 有关在线文件的文章推荐10篇
  10. 详解用MicroService4Net 创建一个微服务