Python font ImageFont and ImageDraw for character support

I use Python image processing libraries to render character images using different fonts.

Here is a snippet of code that I use to iterate over a list of fonts and a list of characters to display an image of that character for each font.

from PIL import Image, ImageFont, ImageDraw
...

image = Image.new('L', (IMAGE_WIDTH, IMAGE_HEIGHT), color=0)
font = ImageFont.truetype(font, 48)
drawing = ImageDraw.Draw(image)
w, h = drawing.textsize(character, font=font)
drawing.text(
            ((IMAGE_WIDTH-w)/2, (IMAGE_HEIGHT-h)/2),
            character,
            fill=(255),
            font=font
)

However, in some cases, the font does not support the character and displays either a black image or a default / invalid character. How can I detect that a character is not supported by the font and handles this case separately?

+7
source share
1 answer

You can use the fontTools library to achieve this:

from fontTools.ttLib import TTFont
from fontTools.unicode import Unicode

font = TTFont('/path/to/font.ttf')

 def has_glyph(font, glyph):
     for table in font['cmap'].tables:
         if ord(glyph) in table.cmap.keys():
             return True
     return False

This function returns whether the character is in the font or not:

>>> has_glyph(font, 'a')
True
>>> has_glyph(font, 'Ä')
True
>>> chr(0x1f603)
'😃'
>>> has_glyph(font, chr(0x1f603))
False
0
source

Source: https://habr.com/ru/post/1691259/


All Articles