Scenario

我有一组名为 32.png,..,126.png 的图像,是与文件名中数字的ASCII可打印字符有关的手写字母,我打算将这些转换为一个字体文件,如 .ttf ,这样我就可以用它输入(基本的)latex字母。

在翻阅了以下文件后 project description 文件 我还没能确定如何在python中把这些图片转换成 .ttf 的字体文件。

我似乎可以把 .png 的图像转换成 .svg 的格式,因为fonttools通常用于字体矢量,但我没有找到一个输出字体文件的方法。因此,我想问一下。

Question

如何在Python中把一组图片(无论是 .png 还是 .svg )转换成 .ttf 的字体?

Attempts

  • After installing fontforge on windows和adding the ../FontForgeBuilds/bin folder to path, Anaconda does not recognize the fontforge module as it throws error:
  • ModuleNotFoundError: No module named 'fontforge' in .svg 文件转换为 .ttf 文件的脚本 .名为 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')
        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] )
        
    1 个评论
    python
    fonts
    svg
    a.t.
    a.t.
    发布于 2020-08-12
    1 个回答
    a.t.
    a.t.
    发布于 2020-08-12
    已采纳
    0 人赞同

    FontForge不是一个python模块,而是独立的软件。因此,与其从python脚本中调用FontForge,不如从fontforge的可执行文件中调用python。由于我想从一个python脚本中创建.ttf格式的字体。我写了一个额外的名为execute.py的python脚本,它执行了一个cmd的命令,该命令执行了执行pythonsvgs2ttf脚本的fontforge。

    The execute.py包含。

    import os
    os.system('cmd /k "fontforge -lang=py -script svgs2ttf examples/example.json"')
    

    The svgs2ttf script is modified from 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')
        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] )
    

    它可以增强转换功能,转换比ab更多的符号,在examples文件夹中包括所有的符号图像来生成字体。

    In response to the comments, here is the contents of 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)", "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": "."