gpt4 book ai didi

python - 如何在不指定绝对路径的情况下使用 PIL.ImageFont.truetype 加载字体文件?

转载 作者:IT老高 更新时间:2023-10-28 21:17:06 27 4
gpt4 key购买 nike

当我在 Windows 中编写代码时,这段代码可以很好地加载字体文件:

ImageFont.truetype(filename='msyhbd.ttf', size=30);

我猜字体位置是在 Windows 注册表中注册的。但是当我将代码移动到 Ubuntu 并将字体文件复制到/usr/share/fonts/时,代码无法找到字体:

 self.font = core.getfont(font, size, index, encoding)
IOError: cannot open resource

如何在不指定绝对路径的情况下让 PIL 找到 ttf 文件?

最佳答案

对我来说,这是在 xubuntu 上工作的:

from PIL import Image,ImageDraw,ImageFont

# sample text and font
unicode_text = u"Hello World!"
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 28, encoding="unic")

# get the line size
text_width, text_height = font.getsize(unicode_text)

# create a blank canvas with extra space between lines
canvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")

# draw the text onto the text canvas, and use blue as the text color
draw = ImageDraw.Draw(canvas)
draw.text((5,5), u'Hello World!', 'blue', font)

# save the blank canvas to a file
canvas.save("unicode-text.png", "PNG")
canvas.show()

enter image description here

Windows 版本

from PIL import Image, ImageDraw, ImageFont

unicode_text = u"Hello World!"
font = ImageFont.truetype("arial.ttf", 28, encoding="unic")
text_width, text_height = font.getsize(unicode_text)
canvas = Image.new('RGB', (text_width + 10, text_height + 10), "orange")
draw = ImageDraw.Draw(canvas)
draw.text((5, 5), u'Hello World!', 'blue', font)
canvas.save("unicode-text.png", "PNG")
canvas.show()

输出同上:

enter image description here

关于python - 如何在不指定绝对路径的情况下使用 PIL.ImageFont.truetype 加载字体文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com