1

Some case study here. I am trying to play with PIL library in Google Colab, and can't get ImageFont to read my originally zipped file. The code:

import requests, zipfile, io
r3 = requests.get('https://sources.archlinux.org/other/community/ttf-roboto/ttf-roboto-hinted-2.138.zip') 
z3 = zipfile.ZipFile(io.BytesIO(r3.content))
z3.extractall()

So far so good, and if I browse my directory with ls, it shows me the elements:

ls

Shows:

LICENSE                          RobotoCondensed-Regular.ttf
__MACOSX/                        Roboto-Italic.ttf
Roboto-BlackItalic.ttf           Roboto-LightItalic.ttf
Roboto-Black.ttf                 Roboto-Light.ttf
Roboto-BoldItalic.ttf            Roboto-MediumItalic.ttf
Roboto-Bold.ttf                  Roboto-Medium.ttf
RobotoCondensed-BoldItalic.ttf   Roboto-Regular.ttf
RobotoCondensed-Bold.ttf         Roboto-ThinItalic.ttf
RobotoCondensed-Italic.ttf       Roboto-Thin.ttf
RobotoCondensed-LightItalic.ttf  sample_data/
RobotoCondensed-Light.ttf

Now let's import ImageFont

from PIL import ImageFont

How do I read the file? If I try this:

# how do I make it work if I read it from the extracted files?
font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)

It fails with an error:

'utf-8' codec can't decode byte 0x80 in position 7: invalid start byte

I know that I can pass a direct link to requests, and it will work:

# it works if we pass a direct link to requests like this:
req = requests.get("https://github.com/googlefonts/roboto/blob/master/src/hinted/Roboto-Regular.ttf?raw=true")
font = ImageFont.truetype(io.BytesIO(req.content), 72)

But how do I read the file from the local memory?

Full image for easier review: enter image description here

delimiter
  • 519
  • 2
  • 10

1 Answers1

1

You only need to provide the filename to ImageFont.truetype(), so change this line:

font = ImageFont.truetype(open("Roboto-BlackItalic.ttf"), 72)

to

font = ImageFont.truetype("Roboto-BlackItalic.ttf", 72)
Mark Setchell
  • 146,975
  • 21
  • 182
  • 306