问题描述
这是一个简短的示例.
from PIL import ImageFont, ImageDraw绘制 = ImageDraw.Draw(图像)# 使用位图字体font = ImageFont.load("arial.pil")draw.text((10, 10), "你好", font=font)# 使用 truetype 字体font = ImageFont.truetype("arial.ttf", 15)draw.text((10, 25), "world", font=font)
我想知道字体是否缺少渲染文本中的任何字形.
当我尝试渲染丢失的字形时,我得到一个空方块.
draw.text((10, 10), chr(1234), font=font)
- 如何以编程方式确定丢失的字形?
- 如何在 ttf 文件中列出可用的字形?
这两个问题几乎一样.
我更喜欢使用 Pillow 来确定我想要什么.也欢迎来自 PyPI 的其他模块.
有'fontTools' 包,其中包含一个用于读取和查询 TrueType 字体的 Python 类.这样的事情是可能的
from fontTools.ttLib import TTFontf = TTFont('/path/to/font/arial.ttf')print(f.getGlyphOrder()) # 顺序中的字形列表# 他们出现了print(f.getReversedGlyphMap() # 从字形名称到 Id 的映射id = f.getGlyphID('Euro') # 欧元字符的内码,# 如果字符,则引发属性错误# 不存在.
从字符到字形的映射通常很复杂,在字体的 cmap 表中定义.这是一个二进制部分,但可以用
检查f.getTableData('cmap')
一个字体可以有多个 cmap 表.freetype 接口也可以读取 ttf 文件.可以使用 freetype 尝试渲染字符,然后查看结果:这会很慢.
将 freetype 导入为 ftface = ft.Face('arial.ttf')face.set_size(25*32)face.load_char(‽)位图 = face.glyph.bitmap.bufferif bitmap == [255, 255, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 255]: 25print("字体中没有interobang")
Here is a short example.
from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
When I try to render a glyph that is missing I get an empty square.
draw.text((10, 10), chr(1234), font=font)
- How to programmatically determine missing glyphs?
- How to list available glyphs in a ttf file?
The two questions are almost the same.
There is the 'fontTools' package, that includes a python class for reading and querying TrueType fonts. Something like this is possible
from fontTools.ttLib import TTFont
f = TTFont('/path/to/font/arial.ttf')
print(f.getGlyphOrder()) # a list of the glyphs in the order
# they appear
print(f.getReversedGlyphMap() # mapping from glyph names to Id
id = f.getGlyphID('Euro') # The internal code for the Euro character,
# Raises attribute error if the character
# isn't present.
The mapping from characters to glyphs is often complex, and is defined in the cmap table of the font. It's a binary section, but can be inspected with
f.getTableData('cmap')
A font can have multiple cmap tables. The freetype interface can also read ttf files. It is possible to use freetype to attempt to render a character, and see the result: this would be slow.
import freetype as ft
face = ft.Face('arial.ttf')
face.set_size(25*32)
face.load_char(‽)
bitmap = face.glyph.bitmap.buffer
if bitmap == [255, 255, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 255, 255]:
print("No interobang in the font")
这篇关于ImageFont 检测丢失的字形(Python Pillow)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!