2

Here is a short example.

from PIL import ImageFont, ImageDraw

draw = ImageDraw.Draw(image)

# use a bitmap font
font = ImageFont.load("arial.pil")

draw.text((10, 10), "hello", font=font)

# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)

draw.text((10, 25), "world", font=font)

I want to know if the font is missing any glyphs from the rendered text.

When I try to render a glyph that is missing I get an empty square.

draw.text((10, 10), chr(1234), font=font)
  • How to programmatically determine missing glyphs?
  • How to list available glyphs in a ttf file?

The two questions are almost the same.

I would prefer using Pillow to determine what I want. Other modules from PyPI are welcome as well.

Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71

1 Answers1

4

There is the 'fontTools' package, that includes a python class for reading and querying TrueType fonts. Something like this is possible

from fontTools.ttLib import TTFont
f = TTFont('/path/to/font/arial.ttf')
print(f.getGlyphOrder())      # a list of the glyphs in the order 
                              # they appear
print(f.getReversedGlyphMap() # mapping from glyph names to Id
id = f.getGlyphID('Euro')     # The internal code for the Euro character, 
                              # Raises attribute error if the character
                              # isn't present.

The mapping from characters to glyphs is often complex, and is defined in the cmap table of the font. It's a binary section, but can be inspected with

f.getTableData('cmap')

A font can have multiple cmap tables. The freetype interface can also read ttf files. It is possible to use freetype to attempt to render a character, and see the result: this would be slow.

import freetype as ft
face = ft.Face('arial.ttf')
face.set_size(25*32)
face.load_char(‽)
bitmap = face.glyph.bitmap.buffer
if bitmap == [255, 255, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 255, 255]:
     print("No interobang in the font")  
James K
  • 3,692
  • 1
  • 28
  • 36