-
Notifications
You must be signed in to change notification settings - Fork 0
/
text.py
208 lines (179 loc) · 7.39 KB
/
text.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import unicodedata
from typing import Literal, Optional, overload
import PIL.Image
import skia
Ink = str | int | tuple[int, int, int] | tuple[int, int, int, int]
def get_color(color: Ink) -> int:
if isinstance(color, int):
return color
elif isinstance(color, str):
c = getattr(skia, "Color" + color.upper())
if isinstance(c, int):
return c
else:
raise ValueError("Unknown Color name")
else:
return skia.Color(*color)
class MultiWriter:
def __init__(self,
size: int = 50,
stroke_width: int = 0,
width: int = 0,
height: int = 0,
word_font_path: str = "static/font/SourceHanSans-Medium.ttf",
emoji_font_path="static/font/NotoColorEmoji.ttf"):
self.fontmgr = skia.FontMgr()
self.size = size
self.width = width
self.height = height
self.stroke_width = stroke_width
# 能从文件来就从文件来,从文件中来不了再从系统里随便找一个
self.emoji_font = skia.Font(
skia.Typeface.MakeFromFile(emoji_font_path) or self.fontmgr.matchFamilyStyleCharacter(
"monospace", skia.FontStyle(), ['zh-cn'], ord('👴')), size)
self.word_font = skia.Font(
skia.Typeface.MakeFromFile(word_font_path) or self.fontmgr.matchFamilyStyleCharacter(
"monospace", skia.FontStyle(), ['zh-cn'], ord('你')), size)
self.builder = skia.TextBlobBuilder()
def analyse_font(self, text: str):
analyse = [[]]
seek = 0 if self.height != 1 else self.word_font.measureText("...")
height = 1
def get_last():
try:
return analyse[-1][-1]
except IndexError:
return None
for char in text:
ord_char = ord(char)
if self.word_font.unicharToGlyph(ord_char):
select_font = self.word_font
elif self.emoji_font.unicharToGlyph(ord_char):
select_font = self.emoji_font
elif (k := get_last()) is not None:
select_font = k[1]
else:
select_font = skia.Font(
self.fontmgr.matchFamilyStyleCharacter("monospace", skia.FontStyle(), ['zh-cn'],
ord_char), self.size)
char_size = select_font.measureText(char)
if (self.width and seek + char_size > self.width) or char == "\n":
height += 1
if height == self.height:
analyse.append([])
seek = self.word_font.measureText("...")
elif height == self.height + 1:
analyse[-1].append(["...", self.word_font])
break
else:
analyse.append([])
seek = 0
if char == "\n":
continue
seek += char_size
if (k := get_last()) and k[1] == select_font:
k[0] += char
else:
analyse[-1].append([char, select_font])
return analyse
def build_textblob(self, analyse):
height = self.size
for line in analyse:
seek = 0
for word, font in line:
self.builder.allocRun(word, font, seek, height)
seek += font.measureText(word)
height += self.size + self.stroke_width
def text2pic(self,
text: str,
color: Ink = 0xFFFFFFFF,
background_color: Optional[Ink] = None,
ensure_width: bool = True) -> skia.Image:
# 为了防止有组合字符写不出来
analyse = self.analyse_font(unicodedata.normalize("NFC", text))
self.build_textblob(analyse)
blob = self.builder.make()
if blob is None:
return skia.Surface(1, 1).makeImageSnapshot()
rect = blob.bounds()
width = max(self.width if self.width and ensure_width else int(rect.right()), 1)
height = ((len(analyse) - 1) * (self.stroke_width + self.size) +
int(self.word_font.getSpacing()))
surface = skia.Surface(width, height)
canvas = surface.getCanvas()
if background_color is not None:
canvas.clear(get_color(background_color))
paint = skia.Paint(AntiAlias=True, Color=get_color(color))
canvas.drawTextBlob(blob, 0, 0, paint)
return surface.makeImageSnapshot()
@overload
def text2pic(text: str,
color: Ink = 0xFFFFFFFF,
size: int = 50,
stroke_width: int = 0,
width: int = 0,
height: int = 0,
background_color: Optional[Ink] = None,
ensure_width: bool = True,
word_font_path: str = "static/font/SourceHanSans-Medium.ttf",
emoji_font_path="static/font/NotoColorEmoji.ttf",
ret_type: Literal["bytes"] = "bytes",
image_type: str = "PNG",
quality: int = 80) -> bytes:
...
@overload
def text2pic(text: str,
color: Ink = 0xFFFFFFFF,
size: int = 50,
stroke_width: int = 0,
width: int = 0,
height: int = 0,
background_color: Optional[Ink] = None,
ensure_width: bool = True,
word_font_path: str = "static/font/SourceHanSans-Medium.ttf",
emoji_font_path: str = "static/font/NotoColorEmoji.ttf",
ret_type: Literal["skia"] = "skia") -> skia.Image:
...
@overload
def text2pic(text: str,
color: Ink = "WHITE",
size: int = 50,
stroke_width: int = 0,
width: int = 0,
height: int = 0,
background_color: Optional[Ink] = None,
ensure_width: bool = True,
word_font_path: str = "static/font/SourceHanSans-Medium.ttf",
emoji_font_path: str = "static/font/NotoColorEmoji.ttf",
ret_type: Literal["PIL"] = "PIL") -> PIL.Image.Image:
...
def text2pic(
text: str,
color: Ink = "WHITE",
size: int = 50,
stroke_width: int = 0,
width: int = 0,
height: int = 0,
background_color: Optional[Ink] = None,
ensure_width: bool = True,
word_font_path: str = "static/font/SourceHanSans-Medium.ttf",
emoji_font_path: str = "static/font/NotoColorEmoji.ttf",
ret_type: Literal["skia", "PIL", "bytes"] = "skia",
*args, **kwargs) -> bytes | skia.Image | PIL.Image.Image:
writer = MultiWriter(size, stroke_width, width, height, word_font_path, emoji_font_path)
image = writer.text2pic(text, color, background_color, ensure_width)
if ret_type == "skia":
return image
elif ret_type == "PIL":
return PIL.Image.fromarray(image.convert(alphaType=skia.kUnpremul_AlphaType))
elif ret_type == "bytes":
image_type = getattr(skia.EncodedImageFormat, "k" + kwargs.get("image_type", "PNG").upper())
quality = kwargs.get("quality", 80)
return image.encodeToData(image_type, quality).bytes()
if __name__ == "__main__":
#text = unicodedata.normalize("NFC", "\n\nā\n\náăà")
text = ""
a = MultiWriter(stroke_width=10)
b = a.text2pic(text).encodeToData(skia.kPNG, 100).bytes()
#with open("test.png", "wb") as f:
# f.write(b)