python - 通过字体名称而不是文件名和跨平台字体选择 PIL.ImageFont

标签 python fonts python-imaging-library

ImageFont.truetype 需要一个文件名才能工作,例如:

font = ImageFont.truetype("ariblk.ttf")  # Arial Black

PIL 有没有办法按名称而不是文件名加载字体?

上下文:我想加载一个粗体(重量很重)的无衬线字体,它可以在任何平台 Windows、Linux、Mac 上工作。

我不认为 ImageFont.truetype("ariblk.ttf") 可以跨平台工作,是否可以使用 ImageFont.truetype("Arial Black") 加载它 或者更好的 ImageFont.truetype("sans-serif;bold") 可以在所有平台上运行?

最佳答案

查看 Pillow 的文档 ImageFont模块,没有这样的选项,没有。

一个方便的解决方法可能是使用 Matplotlib 的 font_manager模块:一个用于跨平台查找、管理和使用字体的模块。 使用 FontPropertiesfindfont ,您应该获得具有给定属性的字体的有效路径,然后您可以在常见的 ImageFont.truetype 调用中使用它。

这是一个小例子,它在我的 Windows 机器上运行良好。不幸的是,我附近没有任何其他操作系统可供测试。

from matplotlib import font_manager
from PIL import Image, ImageDraw, ImageFont

font = font_manager.FontProperties(family='sans-serif', weight='bold')
file = font_manager.findfont(font)
print(file)

img = Image.new('RGB', (400, 300), (255, 255, 255))
draw = ImageDraw.Draw(img)

font = ImageFont.truetype(file, 48)
draw.text((20, 20), 'Hello World', font=font, fill=(255, 0, 0))

img.save('test.png')

打印输出:

...\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\DejaVuSans-Bold.ttf

图像输出:

Output

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
Matplotlib:    3.3.4
Pillow:        8.1.0
----------------------------------------

关于python - 通过字体名称而不是文件名和跨平台字体选择 PIL.ImageFont,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66274858/

相关文章:

python - Pillow中bbox的参数是什么意思?

python - 如何在python3中导入mysqlclient

python - 当子类用 __init__() 调用 super() 时,父类(super class)的对象在哪里/什么?

css - 我可以使用 Google 网络字体自定义字体吗?

c++ - 无法在 Windows CE 中以编程方式卸载字体

python - 导入错误 : cannot import name 'ImageTK'

python - 将本地 dist 包安装到 virtualenv 中

python - 将 pandas 系列转换为对象数组,如 JavaScript 中所示

wpf - 如何在不修改以前的文本的情况下更改 WPF RichTextBox 中的 FontFamily

python - Python 中最快的 2D 卷积或图像过滤器