PIL: OSError: Unknown File Format

Viewed 674

Attempted to use a piece of code from other questions on Stack Overflow. Ran into this piece of code:

from PIL import ImageFont
from urllib.request import urlopen

truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf'
font = ImageFont.truetype(urlopen(truetype_url), size=10)

I got this error:

OSError: unknown file format

I tried other suggestions such as reinstalling PIL, using requests.get and I receive the same error. I checked the link and it does take you to the item in question. Are there other suggestions I can try?

My Goal: Be able to take a font from a link so I do not have to do this locally on my computer.

Thanks!

1 Answers

You can do it like this:

from PIL import Image, ImageFont, ImageDraw
import requests
import io

# Load font from URI
truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'
r = requests.get(truetype_url, allow_redirects=True)
font = ImageFont.truetype(io.BytesIO(r.content), size=24)

# Create a black canvas and get drawing context
canvas = Image.new('RGB', (300,180))
draw = ImageDraw.Draw(canvas)

# Write in our font
draw.text((10, 10), "Got that crazy font", font=font, fill=(255,255,255))
canvas.save('result.png')

enter image description here


As Karl points out in the comments, you can do it with urllib as you were originally intending like this:

from urllib.request import urlopen

truetype_url = 'https://github.com/googlefonts/roboto/blob/main/src/hinted/Roboto-Black.ttf?raw=true'

font = ImageFont.truetype(urlopen(truetype_url), size=10)
Related