from fontTools.ttLib import TTFont from fontTools.pens.basePen import BasePen from reportlab.graphics.shapes import Path from reportlab.lib import colors from reportlab.graphics import renderPM from reportlab.graphics.shapes import Group, Drawing import os
defcheck_out_path(self): """ 检查图片文件输出的路径,如文件夹未创建,则直接创建 """ if os.path.isdir(self.out_path): pass else: os.mkdir(self.out_path)
defdraw_to_image(self): """ 将字体画图输出 """ self.check_out_path() font = TTFont(self.ttf_file) gs = font.getGlyphSet() glyphnames = font.getGlyphNames() n = 0 for i in glyphnames: if i[0] == '.': continue g = gs[i] pen = ReportLabPen(gs, Path(fillColor=colors.black, strokeWidth=5)) g.draw(pen) w, h = g.width, g.width g = Group(pen.path) g.translate(0, 400)
d = Drawing(w, h) d.add(g) image_file = os.path.join(self.out_path, f'{i.replace("uni", "")+"."+self.fmt}') renderPM.drawToFile(d, image_file, self.fmt) n += 1 print(f'第{n}个字体制作完毕,图片为{image_file}!')
if __name__ == '__main__': ttf = TtfToImage('d:/字体反爬/测试用例/途昂1/wKgHGlsV95yAIlpKAADWCPynXQc60..ttf') ttf.draw_to_image()
defget_font_dict(self): res = self.ocr.ocr(self.font_file) res = [row[0] for row in res] res = np.array(res) for x, y in np.argwhere(self.key_array): if self.key_array[x, y] != 'None': self.font_dict[self.key_array[x, y]] = res[x, y]
with open(f'{self.font_file.replace(".png", ".txt")}', 'w', encoding='utf-8') as fin: fin.write(json.dumps(self.font_dict, ensure_ascii=False))
classParseHtml: def__init__(self, html, font_dict_file): self.html_path = html with open(html, 'r', encoding='utf-8') as fin: self.html = fin.read()
with open(font_dict_file, 'r', encoding='utf-8') as fin: self.font_dict = json.loads(fin.read())
defreplace_html(self): for k, v in self.font_dict.items(): p = f"{k.lower()};" self.html = self.html.replace(p, v) with open(self.html_path.replace('.txt', '_new.txt'), 'w', encoding='utf-8') as
fout: fout.write(self.html)