Python PIL:字体粗细和样式

And*_*kha 5 python fonts truetype python-imaging-library pillow

在我的电脑上,我只有一个用于Ubuntu Condensed字体的文件.即:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-C.ttf 
Run Code Online (Sandbox Code Playgroud)

但是,在LibreOffice中,我可以将此字体设为粗体和斜体: 在此输入图像描述

Ubuntu字体测试器网页上,我还可以为Ubuntu Condensed系列设置不同的字体粗细(即常规和粗体)和不同的字体样式(即正常和斜体).在CSS中,这可能转化为:

/* CSS for bold and italic Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: italic;
font-weight: 700;
Run Code Online (Sandbox Code Playgroud)

要么:

/* CSS for regular and normal Ubuntu Condensed font */
font-family: Ubuntu Condensed;
font-style: normal;
font-weight: 400;
Run Code Online (Sandbox Code Playgroud)

但是,当谈到Python的PIL/Pillow时,我找不到ImageFont中任何可以修改字体样式和/或重量的工作选项,除了ImageFont.truetype()函数加载不同的字体文件.

对于"常规"Ubuntu字体(不是Condensed),我可以加载四个单独文件中的一个,以在Python中获得普通,粗体,斜体和粗体+斜体样式:

/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-R.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-RI.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf
/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-BI.ttf
Run Code Online (Sandbox Code Playgroud)

但不适用于Ubuntu Condensed.

所以问题是,是否可以在PIL/Pillow中使用粗体和/或斜体Ubuntu Condensed字体绘制图像?或者至少可以生成四个Ubuntu Condensed文件,以便它可以像Python中的Ubuntu字体一样使用?

fri*_*der 6

您可以使用方法选择所需的字体变体set_variation_by_name

为了获得所有变体,请使用get_variation_names应该为您提供名称列表的方法。

>>> from PIL import ImageFont
>>> 
>>> font = ImageFont.truetype(...)
>>> font.get_variation_names()
[b'Normal', b'Bold', b'Italic', b'Bold, Italic']
>>> font.set_variation_by_name('Italic')
Run Code Online (Sandbox Code Playgroud)

这应该会为您提供所需的字体变体。

  • 根据文档,如果字体不是“变体字体”,即字体文件仅包含一种变体,则会引发“OSError”。如果其他地方有其他变体,它们可能存储在单独的文件中。例如,在 Windows 上,Arial 字体有常规、粗体、斜体、粗斜体等单独的文件。 (3认同)
  • 感谢您的回复。但是,到目前为止我还无法使其工作:我在 get_variation_names 中得到 `File "/userhome/34/amakukha/anaconda3/lib/python3.7/site-packages/PIL/ImageFont.py", line 497, in get_variation_names names = self.font.getvarnames() OSError: invalid argument` 在带有 Pillow 6.2.0 的 Ubuntu 上。MacOS 上的 Pillow 7.1.1 也出现类似错误。 (2认同)