Python ImageFont和ImageDraw检查字体支持的字体

时间:2017-12-23 00:41:59

标签: python python-2.7 unicode fonts python-imaging-library

我正在使用Python的图像处理库来使用不同的字体渲染字符图像。

这是我用来迭代字体列表和字符列表的代码片段,为每种字体输出该字符的图像。

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
)

但是,在某些情况下,字体不支持字符并呈现黑色图像或默认/无效字符。如何检测字体是否支持字符并单独处理该字符?

1 个答案:

答案 0 :(得分:1)

您可以使用fontTools library来实现:

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

此函数返回字体中是否包含字符:

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