gpt4 book ai didi

python - 如何使用python将一组图像转换为字体 `.ttf`文件?

转载 作者:行者123 更新时间:2023-12-04 09:09:35 28 4
gpt4 key购买 nike

设想
我有一组名为 32.png,..,126.png 的图像与文件名中数字的 ASCII 可打印字符有关的手写字母,我打算将它们转换为字体文件,如 .ttf这样我就可以用它输入(基本) latex 字母。
在浏览了 project description 的文档后和 documentation我还不能确定如何将这些图像转换为 .ttf python中的字体文件。
看来我可以转换 .png图像到 .svg格式作为 fonttools 通常用于字体矢量,但我没有找到输出字体文件的方法。因此我想问:
问题
如何将一组图像(.png.svg)转换为 .ttf python中的字体?
尝试

  • 安装后fontforge在 Windows 上并添加 ../FontForgeBuilds/bin文件夹到路径,Anaconda 无法识别 fontforge模块抛出错误:

  • ModuleNotFoundError: No module named 'fontforge' in a script that converts .svg files into .ttf files. The script named svgs2ttf is called with command: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] )

    最佳答案

    FontForge 不是 python 模块,而是独立的软件。因此,不是从 python 脚本调用 FontForge,而是可以从 fontforge 可执行文件调用 python。因为我想在 .ttf 中创建字体从 python 脚本格式化,我编写了一个名为 execute.py 的附加 python 脚本执行 cmd执行执行 python svgs2ttf 的 fontforge 的命令脚本。execute.py包含:

    import os
    os.system('cmd /k "fontforge -lang=py -script svgs2ttf examples/example.json"')
    svgs2ttf脚本修改自 this repository包含:
    # one can run  this script with:
    #fontforge -lang=py -script svgs2ttf examples/example.json

    import sys
    import os.path
    import json
    import fontforge

    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] )
    可以增强转换比 a更多的符号和 b examples 中的符号存储库的文件夹以包含所有符号图像以生成字体。
    回应评论,这里是 the example.json 的内容:
    { "props":
    { "ascent": 96
    , "descent": 32
    , "em": 128
    , "encoding": "UnicodeFull"
    , "lang": "English (US)"
    , "family": "Example"
    , "style": "Regular"
    , "familyname": "Example"
    , "fontname": "Example-Regular"
    , "fullname": "Example Regular"
    }
    , "glyphs":
    { "0x3f": { "src": "question.svg", "width": 128 }
    , "0xab": { "src": "back.svg", "width": 128 }
    , "0x263a": ""
    , "0x2723": "overlap-test.svg"
    , "0x1f304": "outline-test.svg"
    }
    , "sfnt_names":
    [ ["English (US)", "Copyright", "Copyright (c) 2014 by Nobody"]
    , ["English (US)", "Family", "Example"]
    , ["English (US)", "SubFamily", "Regular"]
    , ["English (US)", "UniqueID", "Example 2014-12-04"]
    , ["English (US)", "Fullname", "Example Regular"]
    , ["English (US)", "Version", "Version 001.000"]
    , ["English (US)", "PostScriptName", "Example-Regular"]
    ]
    , "input": "."
    , "output": [ "example.ttf", "example.svg", "example.woff" ]
    , "# vim: set et sw=2 ts=2 sts=2:": false
    }

    关于python - 如何使用python将一组图像转换为字体 `.ttf`文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63380545/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com