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

way*_*way 7 python unicode fonts python-imaging-library python-2.7

我使用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
)
Run Code Online (Sandbox Code Playgroud)

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

kal*_*ann 11

您可以使用fontTools 库来实现此目的:

\n
from fontTools.ttLib import TTFont\nfrom fontTools.unicode import Unicode\n\nfont = TTFont(\'/path/to/font.ttf\')\n\ndef has_glyph(font, glyph):\n    for table in font[\'cmap\'].tables:\n        if ord(glyph) in table.cmap.keys():\n            return True\n    return False\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
>>> has_glyph(font, \'a\')\nTrue\n>>> has_glyph(font, \'\xc3\x84\')\nTrue\n>>> chr(0x1f603)\n\'\'\n>>> has_glyph(font, chr(0x1f603))\nFalse\n
Run Code Online (Sandbox Code Playgroud)\n