我想在 python 中获取字体名称(字体文件描述中存在的标题)。
我查看了该fonttools模块,但找不到任何使用它提取标题的方法。
我怎样才能做到这一点?
以下是使用 fonttools 的方法:
from fontTools import ttLib
font = ttLib.TTFont(fontPath)
fontFamilyName = font['name'].getDebugName(1)
fullName= font['name'].getDebugName(4)
Run Code Online (Sandbox Code Playgroud)
数字1、4是nameID。如果您需要更多信息,请阅读有关 nameID 的文档:https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids
以下是有关命名表的 fonttools 文档:https://fonttools.readthedocs.io/en/latest/ttLib/tables/_n_a_m_e.html
如果您需要更强大的方法来从命名表中获取名称,您可以使用以下逻辑:
import sys
from fontTools import ttLib
from fontTools.ttLib.tables._n_a_m_e import NameRecord
from typing import List
def sortNamingTable(names: List[NameRecord]) -> List[NameRecord]:
"""
Parameters:
names (List[NameRecord]): Naming table
Returns:
The sorted naming table.
Based on FontConfig:
- https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/d863f6778915f7dd224c98c814247ec292904e30/src/fcfreetype.c#L1127-1140
"""
def isEnglish(name: NameRecord) -> bool:
# From: https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/d863f6778915f7dd224c98c814247ec292904e30/src/fcfreetype.c#L1111-1125
return (name.platformID, name.langID) in ((1, 0), (3, 0x409))
# From: https://github.com/freetype/freetype/blob/b98dd169a1823485e35b3007ce707a6712dcd525/include/freetype/ttnameid.h#L86-L91
PLATFORM_ID_APPLE_UNICODE = 0
PLATFORM_ID_MACINTOSH = 1
PLATFORM_ID_ISO = 2
PLATFORM_ID_MICROSOFT = 3
# From: https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/d863f6778915f7dd224c98c814247ec292904e30/src/fcfreetype.c#L1078
PLATFORM_ID_ORDER = [
PLATFORM_ID_MICROSOFT,
PLATFORM_ID_APPLE_UNICODE,
PLATFORM_ID_MACINTOSH,
PLATFORM_ID_ISO,
]
return sorted(names, key=lambda name: (PLATFORM_ID_ORDER.index(name.platformID), name.platEncID, -isEnglish(name), name.langID))
def get_font_names(font: ttLib.TTFont, nameID: int) -> List[NameRecord]:
"""
Parameters:
font (ttLib.TTFont): Font
nameID (int): An ID from the naming table. See: https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids
Returns:
A list of each name that match the nameID code.
You may want to only use the first item of this list.
"""
names = sortNamingTable(font['name'].names)
return list(filter(lambda name: name.nameID == nameID, names))
def main():
font_path = r"FONT_PATH"
font = ttLib.TTFont(font_path)
print(get_font_names(font, 1))
if __name__ == "__main__":
sys.exit(main())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4006 次 |
| 最近记录: |