简体   繁体   中英

How to use python PIL ImageFont.truetype()?

I'm trying to load a font through the ImageFont.truetype() command in the PIL python package.

I've looked at the documentation here: https://pillow.readthedocs.io/en/stable/reference/ImageFont.html?highlight=imagefont but can't figure out what I'm doing wrong.

I've downloaded the font I want, put it in the same directory as my python script (which is also my working directory). My code is:

from pillow import ImageFont
font = ImageFont.truetype('Roboto-Bold.ttf', size=10)

I get this error:

  File "C:\Users\myusername\AppData\Local\anaconda3\lib\site-packages\PIL\ImageFont.py", line 161, in __init__
    font, size, index, encoding, layout_engine=layout_engine

OSError: cannot open resource

I've tried other .ttf files, adding my working directory to sys.path , and using the full path to .ttf file. All those attempts yielded the same error. Any ideas what I've done wrong?

Okay. It looks like I had a piece of code that ran ImageFont.truetype('Roboto-Bold.ttf', size=10) too many times so the operating system eventually stopped opening the font file correctly.

Don't be dumb like me and read in fonts in a recursive function.

Related reading: https://github.com/python-pillow/Pillow/issues/3730

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM