-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPicClass.py
71 lines (69 loc) · 2.53 KB
/
PicClass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import os
import base64
from PIL import ImageFont,ImageDraw,Image
from io import BytesIO
FILE_PATH = os.path.dirname(__file__)
class ImgText:
FONTS_PATH = os.path.join(FILE_PATH,'data')
FONTS = os.path.join(FONTS_PATH,'msyh1.otf')
font = ImageFont.truetype(FONTS, 14)
def __init__(self, text):
# 预设宽度 可以修改成你需要的图片宽度
self.width = 600
# 文本
self.text = text
# 段落 , 行数, 行高
self.duanluo, self.note_height, self.line_height, self.drow_height = self.split_text()
def get_duanluo(self, text):
txt = Image.new('RGBA', (400, 800), (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.text.split('\n'):
duanluo, line_height, line_count = self.get_duanluo(text)
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
drow_height = total_lines * line_height
return allText, total_height, line_height, drow_height
def draw_text(self):
"""
绘图以及文字
:return:
"""
im = Image.new("RGB", (600, self.drow_height), (255, 255, 255))
draw = ImageDraw.Draw(im)
# 左上角开始
x, y = 0, 0
for duanluo, line_count in self.duanluo:
draw.text((x, y), duanluo, fill=(0, 0, 0), font=ImgText.font)
y += self.line_height * line_count
bio = BytesIO()
im.save(bio, format='PNG')
base64_str = 'base64://' + base64.b64encode(bio.getvalue()).decode()
mes = f"[CQ:image,file={base64_str}]"
return mes