I'm attempting to write a program that places text onto an image, I'm trying to get my head round PIL and have run into the error: OSError: cannot open resource. This is my first python program so apologies if the error is obvious.
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()
I get the error:
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
I fixed the problem by using default font.
font = ImageFont.load_default()
If you just need to put some text (font style is not matter to you) then this might be a simple solution.
font = ImageFont.load_default()
draw = ImageDraw.Draw(pil_img)
draw.text(( 20, 32), "text_string", (255,0,0), font=font)
from PIL import Image, ImageDraw, ImageFont
im = Image.open("mak.png")
font_type = ImageFont.truetype("arial.ttf", 18)
draw = ImageDraw.Draw(im)
draw.text(xy=(120, 120), text= "download font you want to use", fill=(255,69,0), font=font_type)
im.show()
Its "arial.ttf" not "Arial.ttf"
Here is the link to download arial.ttf font.
I have also met this issue on Windows 10 Pro with PIL 5.3.0.
On my machine, the error is caused by non-ASCII font file names. If I change the the font name to only contain ASCII characters, I can open the font without any error.
Edit (2019-07-29): this is indeed a bug with ImageFont.truetype()
method and it has been fixed in this pull request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With