Skip to content

Instantly share code, notes, and snippets.

@kunzhipeng
Created April 15, 2020 02:36
Show Gist options
  • Save kunzhipeng/f8a7f2f63354dcb55890a02084280211 to your computer and use it in GitHub Desktop.
Save kunzhipeng/f8a7f2f63354dcb55890a02084280211 to your computer and use it in GitHub Desktop.
将字体文件内各字体导出图片存储,并建立一个Excel索引
# coding: utf-8
# 将字体文件内各字体导出图片存储
# 在https://my.oschina.net/colin86/blog/1842419基础上修改
import os
import xlsxwriter
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, scale
class ReportLabPen(BasePen):
"""A pen for drawing onto a reportlab.graphics.shapes.Path object."""
def __init__(self, glyphSet, path=None):
BasePen.__init__(self, glyphSet)
if path is None:
path = Path()
self.path = path
def _moveTo(self, p):
(x,y) = p
self.path.moveTo(x,y)
def _lineTo(self, p):
(x,y) = p
self.path.lineTo(x,y)
def _curveToOne(self, p1, p2, p3):
(x1,y1) = p1
(x2,y2) = p2
(x3,y3) = p3
self.path.curveTo(x1, y1, x2, y2, x3, y3)
def _closePath(self):
self.path.closePath()
def Font2Images(fontFile, imagePath, fmt="png"):
"""将字体文件内各字体导出图片存储
fontFile - 要处理的字体文件路径;
imagePath - 保存图片的目录;
"""
# 将图片列表存Excel文件中
xlsxFilePath = '{}-images.xlsx'.format(fontFile)
workbook = xlsxwriter.Workbook(xlsxFilePath)
worksheet = workbook.add_worksheet()
worksheet.set_column(0, 0, 18)
worksheet.set_default_row(80)
worksheet.write_string(0, 0, 'Image')
worksheet.write_string(0, 1, u'Code(勿修改)')
worksheet.write_string(0, 2, u'Char')
imagePath = os.path.join(imagePath, os.path.splitext(os.path.basename(fontFile))[0])
if not os.path.exists(imagePath):
os.mkdir(imagePath)
font = TTFont(fontFile)
gs = font.getGlyphSet()
glyphNames = font.getGlyphNames()
row_i = 1
for name in glyphNames:
if name[0] == '.':# 跳过'.notdef', '.null'
continue
g = gs[name]
pen = ReportLabPen(gs, Path(fillColor=colors.red))
g.draw(pen)
w, h = g.width + 10, g.width + 10
g = Group(pen.path)
g.translate(0, 100)
d = Drawing(w, h)
d.add(g)
if name.startswith('uni'):
name = name[3:]
imageFile = imagePath + "/" + name + ".png"
pil_img = renderPM.drawToPIL(d)
w, h = pil_img.size
# 缩放到10%:
pil_img.thumbnail((w/float(10), h/float(10)))
# 保存到文件
pil_img.save(imageFile)
print '"{}" saved.'.format(imageFile)
# 插入图片到Excel
worksheet.insert_image(row_i, 0, imageFile, {'positioning': 1})
worksheet.write_string(row_i, 1, name)
row_i += 1
workbook.close()
print '#' * 66
print 'Font file: "{}"'.format(fontFile)
print 'Total {} chars found.'.format(row_i - 1)
print 'Images save directory: "{}"'.format(imagePath)
print 'Xlsx file save path: "{}"'.format(xlsxFilePath)
print '#' * 66
if __name__ == '__main__':
# 测试
Font2Images(fontFile='fonts/N2BQFizNQ7aV6gymJy75hcEXV7Bqqcah.woff', imagePath='fonts')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment