首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态选择文本消息大小并在图像文件中写入(对齐=证明)

动态选择文本消息大小并在图像文件中写入(对齐=证明)
EN

Stack Overflow用户
提问于 2019-08-11 11:39:49
回答 1查看 184关注 0票数 0

我有一个从网上收集短信的代码。邮件大小从20-500字不等。我想在图像文件中写入文本,条件如下:

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

我写了这段代码,但没有得到想要的结果。

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-15 21:10:22

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

代码语言:javascript
复制
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')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57449664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档