首页 > 解决方案 > 动态选择文本消息大小并写入图像文件(对齐=对齐)

问题描述

我有一个从互联网收集短信的代码。消息大小从 20-500 字不等。我想在具有以下条件的图像文件中写入文本:

  1. 图像大小应根据字符串大小和书面中心对齐方式动态变化。
  2. 图像背景应为黑色。
  3. 测试颜色应该是随机的(从颜色列表文件中选择)
  4. 测试字体应该是随机的(从字体列表文件中挑选)

我已经编写了此代码,但无法获得所需的结果。

from PIL import Image, ImageDraw, ImageFont
import textwrap

font_list = []
color_list = []

astr = 'NRB Bearing Limited has informed the Exchange regarding Pursuant to Regulation 44(3) of the Listing Regulations, we enclose herewith the following in respect of the 54th Annual General Meeting (AGM) of the Company held on Friday, August 9, 2019 at 3:30 p.m.; at the M. C. Ghia Hall, Dubash Marg, Mumbai 400 001.1. Disclosure of the voting results of the businesses transacted at the AGM as required under Regulation 44(3) of the SEBI Listing Regulations.2. Report of the scrutinizer dated August 10, 2019, pursuant to Section 108 of the Companies Act, 2013.We request you to kindly take the same on record'
para = textwrap.wrap(astr, width=100)

MAX_W, MAX_H = 1200, 600
im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('C://Users//Alegreya//Alegreya-RegularItalic.ttf', 18)

current_h, pad = 100, 20
for line in para:
    w, h = draw.textsize(line, font=font)
    draw.text(((MAX_W - w) / 2, current_h), line, font=font)
    current_h += h + pad

im.save('C://Users//greeting_card.png')

标签: pythonpython-3.ximagepython-imaging-libraryword-wrap

解决方案


ImageDraw.text 处理多行文本并考虑间距等。

from PIL import Image, ImageDraw, ImageFont
import textwrap
import random

font_list = ['arial', 'calibri', ...]
color_list = ['red', 'blue', ...]

astr = 'NRB Bearing Limited has informed the Exchange regarding Pursuant to Regulation 44(3) of the Listing Regulations ...'
para = textwrap.wrap(astr, width=100)
para = '\n'.join(para)

MAX_W, MAX_H = 1200, 600
im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)

# randomly pick a font
_idx = random.randint(0, len(font_list)-1)
font_name = font_list[_idx]
font = ImageFont.truetype(font_name, 18)
# pick a color
_idx = random.randint(0, len(color_list )-1)
color = color_list[_idx]

current_h = 100
text_width, text_height = draw.textsize(para, font=font)

draw.text(((MAX_W - text_width) / 2, current_h), para, font=font, fill=color,  align='center')

im.save('C://Users//greeting_card.png')

推荐阅读