Search code examples
pythonfontsdatasettypography

Batch ttf files to per-glyph-image


I have a big dataset of google fonts in ttf file format.

I'd like to convert all their glyphs into individual images, how would I do this?

I found this DrawBot script, but it only allows for a single ttf file to be converted.


Solution

  • There is a possibility to make it using fontforge. You need to install it for you OS first.

    Here's the code adapted from superuser.com. Let's call the file ttf2pngs.py.

    import os
    from fontforge import *
    
    font = open(os.sys.argv[1])
    for glyph in font:
        if font[glyph].isWorthOutputting():
            font[glyph].export(font[glyph].glyphname + ".png")
    

    Don't be alarmed by "package not found" warning on fontforge import. Fontforge knows about Python when you run it's commands from the terminal. You can run your script from the terminal as:

    fontforge -script ttf2pngs.py YOURFONT.ttf
    

    If you want to make it for several fonts in your folder, you can also create a separate Python script like the following (also adding destination folder in the script above):

    import os
    
    fonts = os.listdir(FOLDER_FONTS)
    for font in fonts:
        os.makedirs(FOLDER_LETTERS + font.split(".")[0], exist_ok=True)
        os.system('cmd /c "fontforge -lang=py -script ttf2pngs.py %s %s"' % (FOLDER_FONTS + font, FOLDER_LETTERS))