python使用fontTools对较大的TTF字体文件进行缩包,仅挑出使用到的字符
目前在开发网页小游戏,使用的ttf字体文件太大了足有十多M。公司一直有开发多语言游戏的习惯 所以所有文本都会集中的一个配置文件中(方便翻译其他语言),所以就考虑挑出游戏使用到的字符,从而缩小ttf字体,减少初期进入游戏的下载量。测试了一下效果还是挺好的,12.8M >> 0.6M。我的python 版本是 3.10.6。首先安装 fontTools。可以根据自己的需求进行调整。
·
目前在开发网页小游戏,使用的ttf字体文件太大了足有十多M。公司一直有开发多语言游戏的习惯 所以所有文本都会集中的一个配置文件中(方便翻译其他语言),所以就考虑挑出游戏使用到的字符,从而缩小ttf字体,减少初期进入游戏的下载量。
网上搜到一篇参考链接
测试了一下效果还是挺好的,12.8M >> 0.6M
我的python 版本是 3.10.6
首先安装 fontTools
pip install fontTools
完整脚本如下:
注意: 这里的json要求是简单的key:value格式,例如:
{
"ok": "好的",
"cancel": "取消",
... ...
}
可以根据自己的需求进行调整
#!/usr/bin/python
# coding=UTF-8
import sys
import json
import os
from fontTools.ttLib import TTFont
from fontTools import subset
#source_font: 全量TTF字体源文件
#json_file: 字段的json文件
#out_file: 导出的字体文件
def generate(source_font, json_file, out_file):
all_chars = []
checker = {}
with open(json_file, 'r', encoding='utf-8') as f:
text_data = json.load(f)
for key, value in text_data.items():
for char in value:
uid = ord(char)
if uid not in checker:
checker[uid] = True
all_chars.append(char)
#所有文本
text = ''.join(all_chars)
#TTF源文
#font = TTFont(source_font) NOTE: 这一版在源文件不变的情况下 生成的字体包md5会发生变化 改成下边这种方式
font = subset.load_font(source_font, subset.Options())
#挑出需要的字符
subsetter = subset.Subsetter()
subsetter.populate(text=text)
subsetter.subset(font)
# 生成输出文件
subset.save_font(font, out_file, subset.Options())
font.close()
if __name__ == '__main__':
nargv = len(sys.argv)-1
if nargv< 2 or nargv>3:
print("you need input 2 or 3 args:\n param@1 is a fully ttf file\n param@2 is a json file whose values are the characters you need\n param@3 is optional, you can determine the outfile name by this param, default value in picked.ttf")
exit(-1)
source_font = sys.argv[1]
if not os.path.exists(source_font):
print('please source font ttf file:%s is invalid!'.format(source_font))
exit(-1)
json_file = sys.argv[2]
if not os.path.exists(json_file):
print('json file:%s is not valid!'.format(source_font))
exit(-1)
out_file = "picked.ttf"
if nargv == 3:
out_file = sys.argv[3]
generate(source_font, json_file, out_file)
更多推荐
所有评论(0)