from PIL import Image, ImageDraw, ImageFont
class ImgText:
font = ImageFont.truetype("PingFang Regular.otf", 70)
def __init__(self, title, content, size, backColor):
# 预设宽度 可以修改成你需要的图片宽度
self.width = 900
self.size = size
self.title = title
self.content = content
self.backColor = backColor
# 文本
# self.text = text
# 段落 , 行数, 行高
self.duanluo, self.note_height, self.line_height = self.split_text()
def get_duanluo(self, text):
txt = Image.new('RGBA',self.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(txt)
# 所有文字的段落
duanluo = ""
# 宽度总和
sum_width = 0
# 几行
line_count = 1
# 行高
line_height = 0
for char in text:
width, height = draw.textsize(char, ImgText.font)
sum_width += width
if sum_width > self.width: # 超过预设宽度就修改段落 以及当前行数
line_count += 1
sum_width = 0
duanluo += '\n'
duanluo += char
line_height = max(height, line_height)
if not duanluo.endswith('\n'):
duanluo += '\n'
return duanluo, line_height, line_count
def split_text(self):
# 按规定宽度分组
max_line_height, total_lines = 0, 0
allText = []
for text in self.content.split('\n'):
duanluo, line_height, line_count = self.get_duanluo(self.content)
max_line_height = max(line_height, max_line_height)
total_lines += line_count
allText.append((duanluo, line_count))
line_height = max_line_height
total_height = total_lines * line_height
return allText, total_height, line_height
def RGB_to_Hex(self, tmp):
rgb = tmp.split(',') # 将RGB格式划分开来
strs = '#'
for i in rgb:
num = int(i) # 将str转int
# 将R、G、B分别转化为16进制拼接转换并大写
strs += str(hex(num))[-2:].replace('x', '0').upper()
# print(strs)
# color = RGB_to_Hex('249,204,190')
img = Image.new("RGBA", self.size, strs)
img.save("temp/back.png")
def draw_text(self):
self.RGB_to_Hex(self.backColor)
"""
绘图以及文字
:return:
"""
note_img = Image.open("temp/back.png").convert("RGBA")
draw = ImageDraw.Draw(note_img)
# header = 'this is a title'
# font_type = 'ABACE-PFB-2.ttf'
font_type = 'PingFangHK.otf'
color = "#FFFFFF"
header_font = ImageFont.truetype(font_type, 110)
header_x = 100
header_y = 100
print(self.title)
draw.text((header_x, header_y), u'%s' % self.title, fill=(255, 255, 255), font=header_font)
# 左上角开始
x, y = 100, 300
for duanluo, line_count in self.duanluo:
draw.text((x, y), duanluo, fill=(255, 255, 255), font=self.font)
y += self.line_height * line_count
note_img.show()
note_img.save("temp/backResult.png")
#
if __name__ == '__main__':
size_6 = (2688, 1242)
size_5 = (2208, 1242)
title = "title"
content = "sadjklsjdklasjdl"
color = ('2,213,255')
n = ImgText(title,content,size_5,color)
n.draw_text()
网友评论