How I can load a font file with PIL.ImageFont.truetype in replit

Viewed 237

I'm trying to make this welcome card thingy in discord.py and I'm running my bot on replit.com as of now.

font = ImageFont.truetype("arial.ttf", 28)

I got some examples and it worked great as long as I'm running it on my PC but wen I get to replit.com it gives the error saying

Command raised an exception: OSError: cannot open resource

How should I go about correcting this?

1 Answers

I don't know discord or replit but presume the issue is that you can't upload your binary font file.

If so, you have a couple of options:

  • find your desired font online somewhere and use requests.get(URL) to grab it in your code on replit, or
  • make a base64 variable in your code and decode it

The first option is covered here.

Let's look at the second. Say your font is called /Fonts/funky.ttf on your PC. Now you want that in base64 which you can do with a commandline tool on your local PC:

base64 < /Fonts/funky.txt

That will make a long string of characters. Copy it, and in your Python code add a string called font64 and set it equal to the pasted string, i.e.

font64 = 'PASTED STRING'

Now in your code you can convert the string back from base64 to binary, then wrap it in a BytesIO to make it look like a file and load it:

import base64
import io
from PIL import ImageFont

font64 = 'PASTED STRING'

# decode from base64 to binary
binary = base64.b64decode(font64)

# wrap in BytesIO to make file-like object
FileLike = io.BytesIO(binary)

# load font
font = ImageFont.truetype(FileLike, 28)
Related