简体   繁体   English

如何从python中的字体文件中获取字体名称(标题)

[英]How to get the font name (title) from a font file in python

I want to get the font name (the title present in the description of the font file) in python.我想在 python 中获取字体名称(字体文件描述中的标题)。

在此处输入图像描述

I looked at the fonttools module but could not find any way to extract the title using it.我查看了fonttools模块,但找不到使用它提取标题的任何方法。

How can I do this?我怎样才能做到这一点?

You can use external tools like otfinfo to extract font meta.您可以使用otfinfo等外部工具来提取字体元数据。

otfinfo reports information about the named OpenType font files. otfinfo报告有关命名 OpenType 字体文件的信息。

$ otfinfo --info raleway.ttf       
Family:              Raleway Light
Subfamily:           Regular
Full name:           Raleway Light
PostScript name:     Raleway-Light
Preferred family:    Raleway
Preferred subfamily: Light

You can call it using subprocess in python and filter desired result using regular expression.您可以在 python 中使用 subprocess 调用它,并使用正则表达式过滤所需的结果。

import subprocess
import re

font_file = "/home/user/raleway.ttf"
command = "otfinfo"
params = ["--info"]
result = subprocess.run([command, *params, font_file], stdout=subprocess.PIPE).stdout
font_name_re = re.compile(r"Full name:\s*(.*)")
font_name = font_name_re.findall(result.decode())
print(font_name[0])

Output: Raleway Light输出:雷威灯

Here is how you could do it with fonttools:以下是使用 fonttools 的方法:

from fontTools import ttLib
font = ttLib.TTFont(fontPath)
fontFamilyName = font['name'].getDebugName(1)
fullName= font['name'].getDebugName(4)

The number 1, 4 are nameID.数字 1、4 是 nameID。 If you need anything more, read this documentation about nameID: https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids如果您需要更多信息,请阅读有关 nameID 的文档: https ://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids

Here is fonttools documentation about the naming table: https://fonttools.readthedocs.io/en/latest/ttLib/tables/_n_a_m_e.html这是关于命名表的 fonttools 文档: https ://fonttools.readthedocs.io/en/latest/ttLib/tables/_n_a_m_e.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM