I am using Python's image processing libraries to render images of characters using different fonts.
Here's a snippet of the code that I'm using to iterate through a list of fonts and a list of characters to output 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 doesn't support a character and renders either a black image or a default/invalid character. How can I detect that the character isn't supported by a font and handle that case separately?
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 a character is contained in a font or not:
>>> has_glyph(font, 'a')
True
>>> has_glyph(font, 'Ä')
True
>>> chr(0x1f603)
'😃'
>>> has_glyph(font, chr(0x1f603))
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With