【问题标题】:Python ImageFont and ImageDraw check font for character supportPython ImageFont 和 ImageDraw 检查字体是否支持字符
【发布时间】:2018-06-05 12:56:35
【问题描述】:

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

这是我用来遍历字体列表和字符列表以输出每种字体的该字符的图像的代码的 sn-p。

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
)

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2014-06-01
      • 2011-07-13
      • 2019-08-17
      • 2013-11-06
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多