我正在尝试编写一个将文本放置到图像上的程序,我正在尝试了解 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
最佳答案
我通过使用 default font 修复了该问题。
font = ImageFont.load_default()
如果您只需要输入一些文本(字体样式对您来说并不重要),那么这可能是一个简单的解决方案。
font = ImageFont.load_default()
draw = ImageDraw.Draw(pil_img)
draw.text(( 20, 32), "text_string", (255,0,0), font=font)
关于image - PIL 问题,OSError : cannot open resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47694421/