Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL Issue, OSError: cannot open resource

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
like image 916
Laurence Maskell Avatar asked Dec 07 '17 11:12

Laurence Maskell


3 Answers

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)
like image 154
Uzzal Podder Avatar answered Oct 15 '22 04:10

Uzzal Podder


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.

like image 15
Kartik Avatar answered Oct 15 '22 05:10

Kartik


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.

like image 9
jdhao Avatar answered Oct 15 '22 05:10

jdhao