import numpy
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
import os
def create(text: str, font_filepath: str, font_size: int = 32, width: int = 512, line_padding: int = 16, bgc: str = '#000000', color: str = '#ffffff') -> numpy.ndarray:
"""创建文本块。
Parameters
----------
text : str
待绘制文本
font_filepath : str
字体文件路径
font_size : int, optional
文字像素高度, by default 32
width : int, optional
单行最大宽度, by default 512
line_padding : int, optional
像素行距, by default 16
bgc : str, optional
背景色, by default '#000000'
color : str, optional
前景色, by default '#ffffff'
Returns
-------
numpy.ndarray
[description]
"""
bg = Image.new(mode='RGB', size=(width, font_size), color=bgc)
font_ = ImageFont.truetype(font_filepath, font_size)
t_draw = ImageDraw.Draw(bg)
lines = []
index = 0
for i in range(len(text)):
tw, _ = t_draw.textsize(text[index:i+1], font=font_)
if tw > width:
lines.append(text[index:i])
index = i
lines.append(text[index:])
length = len(lines)
bg = Image.new(mode='RGBA', size=(width, (font_size*length+line_padding*(length-1))), color=bgc)
t_draw = ImageDraw.Draw(bg)
for i in range(len(lines)):
t_draw.text(xy=(0, i*(font_size+line_padding)), text=lines[i], font=font_, fill=color)
return numpy.array(bg)
if __name__ == '__main__':
plt.imshow(Image.fromarray(create(text=''.join([chr(e) for e in range(32, 127)])+'简体中文', font_filepath='/usr/local/share/fonts/sim/simsun.ttc')))
plt.show()
|