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
模块:一个用于跨平台查找、管理和使用字体的模块。 使用 FontProperties
和 findfont
,您应该获得具有给定属性的字体的有效路径,然后您可以在常见的 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
图像输出:
----------------------------------------
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/