PIL 问题,OSError:无法打开资源

新手上路,请多包涵

我正在尝试编写一个将文本放置到图像上的程序,我正试图了解 PIL 并遇到错误:OSError:无法打开资源。这是我的第一个 python 程序,如果错误很明显,我们深表歉意。

 from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

im = Image.open("example.jpg")
font_type = ImageFont.truetype("Arial.ttf", 18)
draw = ImageDraw.Draw(im)
draw.text(xy=(50, 50), text= "Text One", fill =(255,69,0), font = font_type)
im.show()

我收到错误:

 Traceback (most recent call last):
File "C:\Users\laurence.maskell\Desktop\attempt.py", line 7, in <module>
font_type = ImageFont.truetype("Arial.ttf", 18)
File "C:\Python34\lib\site-packages\PIL\ImageFont.py", line 259, in truetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Python34\lib\site-packages\PIL\ImageFont.py", line 143, in __init__
self.font = core.getfont(font, size, index, encoding,
layout_engine=layout_engine)
OSError: cannot open resource

原文由 Laurence Maskell 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

我使用 默认字体 解决 了这个问题。

 font = ImageFont.load_default()

如果您只需要放置一些文本(字体样式对您来说无关紧要),那么这可能是一个简单的解决方案。

 font = ImageFont.load_default()

draw = ImageDraw.Draw(pil_img)
draw.text(( 20, 32), "text_string", (255,0,0), font=font)

原文由 Uzzal Podder 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进