Python中如何通过字体名称获取字体路径?
解决PIL.ImageFont使用通用字体名称的问题
一、通过通用字体名称获取字体路径
你可以借助fonttools库解析系统字体文件,匹配通用名称后返回路径,步骤如下:
- 先安装依赖库:
pip install fonttools
- 编写获取路径的代码:
from tkinter.font import families from fonttools.ttLib import TTCollection, TTFont import os def find_font_path(target_name): # 定义各系统的字体目录 system_font_dirs = [ "/Library/Fonts", # macOS "/usr/share/fonts", # Linux 系统字体 "/usr/local/share/fonts", # Linux 用户安装字体 os.path.join(os.environ["WINDIR"], "Fonts") # Windows ] for dir_path in system_font_dirs: if not os.path.isdir(dir_path): continue # 遍历所有字体文件 for root, _, files in os.walk(dir_path): for file in files: if file.lower().endswith((".ttf", ".otf", ".ttc")): full_path = os.path.join(root, file) try: # 处理字体集合文件(.ttc) if file.lower().endswith(".ttc"): ttc = TTCollection(full_path) for font in ttc: # 获取字体的通用名称(name ID 4) font_full_name = font["name"].getDebugName(4) if target_name == font_full_name: return full_path else: ttfont = TTFont(full_path) font_full_name = ttfont["name"].getDebugName(4) if target_name == font_full_name: return full_path except Exception: # 跳过损坏或无法解析的字体文件 continue return None # 示例:获取"微软雅黑"的路径 font_path = find_font_path("微软雅黑") if font_path: print(f"找到字体路径:{font_path}") else: print("未找到目标字体")
这个方法会遍历系统字体目录,解析每个字体文件的元数据,匹配你传入的通用字体名称,返回对应的文件路径。
二、能否直接在ImageFont.truetype()中使用通用名称?
PIL的ImageFont.truetype()不支持直接传入通用字体名称,它要求传入具体的字体文件路径,或者在部分系统中可以传入字体文件名(比如"Arial.ttf"),但这种方式跨系统兼容性很差——不同系统的字体文件名可能存在差异,比如部分字体在Windows和macOS上的文件名不一致。
所以最稳妥的方式还是先通过上面的方法获取字体路径,再将路径传给ImageFont.truetype():
from PIL import ImageFont font_path = find_font_path("Arial") if font_path: font = ImageFont.truetype(font_path, 40) # 后续使用该字体处理图片
内容的提问来源于stack exchange,提问作者Akascape
相关产品推荐
相关产品推荐

