【发布时间】:2020-08-12 13:46:21
【问题描述】:
场景
我有一组名为 32.png,..,126.png 的手写字母图像,这些图像与文件名中数字的 ASCII 可打印字符有关,我打算将这些图像转换为字体文件,例如 .ttf,以便我可以键入 (基本)乳胶字母。
在浏览了 fonttools 的 project description 和 documentation 的文档后,我还不能确定如何在 python 中将这些图像转换为 .ttf 字体文件。
看来我可以将 .png 图像转换为 .svg 格式,因为 fonttools 通常用于字体矢量,但我没有找到输出字体文件的方法。因此我想问:
问题
如何在 python 中将一组图像(.png 或.svg)转换为.ttf 字体?
尝试
- 在 Windows 上安装 fontforge 并将
../FontForgeBuilds/bin文件夹添加到路径后,Anaconda 无法识别fontforge模块,因为它会抛出错误:
ModuleNotFoundError: No module named 'fontforge'在a script that converts.svgfiles into.ttffiles。名为svgs2ttf的脚本使用命令:python svgs2ttf.py examples/example.json调用。
import sys
import os.path
import json
import fontforge
#python svgs2ttf.py examples/example.json
IMPORT_OPTIONS = ('removeoverlap', 'correctdir')
try:
unicode
except NameError:
unicode = str
def loadConfig(filename='font.json'):
with open(filename) as f:
return json.load(f)
def setProperties(font, config):
props = config['props']
lang = props.pop('lang', 'English (US)')
family = props.pop('family', None)
style = props.pop('style', 'Regular')
props['encoding'] = props.get('encoding', 'UnicodeFull')
if family is not None:
font.familyname = family
font.fontname = family + '-' + style
font.fullname = family + ' ' + style
for k, v in config['props'].items():
if hasattr(font, k):
if isinstance(v, list):
v = tuple(v)
setattr(font, k, v)
else:
font.appendSFNTName(lang, k, v)
for t in config.get('sfnt_names', []):
font.appendSFNTName(str(t[0]), str(t[1]), unicode(t[2]))
def addGlyphs(font, config):
for k, v in config['glyphs'].items():
g = font.createMappedChar(int(k, 0))
# Get outlines
src = '%s.svg' % k
if not isinstance(v, dict):
v = {'src': v or src}
src = '%s%s%s' % (config.get('input', '.'), os.path.sep, v.pop('src', src))
g.importOutlines(src, IMPORT_OPTIONS)
g.removeOverlap()
# Copy attributes
for k2, v2 in v.items():
if hasattr(g, k2):
if isinstance(v2, list):
v2 = tuple(v2)
setattr(g, k2, v2)
def main(config_file):
config = loadConfig(config_file)
os.chdir(os.path.dirname(config_file) or '.')
font = fontforge.font()
setProperties(font, config)
addGlyphs(font, config)
for outfile in config['output']:
sys.stderr.write('Generating %s...\n' % outfile)
font.generate(outfile)
if __name__ == '__main__':
if len(sys.argv) > 1:
main(sys.argv[1])
else:
sys.stderr.write("\nUsage: %s something.json\n" % sys.argv[0] )
【问题讨论】: