-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Closed
Labels
Description
What did you do?
Pass Path object instead of str to ImageFont.truetype(). IMO this should work if I understand the docs correctly.
from PIL import ImageFont
from pathlib import Path
font_path = Path("path/to/your/font")
font = ImageFont.truetype(font_path, 12)What did you expect to happen?
Get back a font object.
What actually happened?
I get a type error saying that I cannot pass a Path object.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mauro/.pyenv/versions/test_env/lib/python3.10/site-packages/PIL/ImageFont.py", line 797, in truetype
return freetype(font)
File "/home/mauro/.pyenv/versions/test_env/lib/python3.10/site-packages/PIL/ImageFont.py", line 794, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "/home/mauro/.pyenv/versions/test_env/lib/python3.10/site-packages/PIL/ImageFont.py", line 226, in __init__
self.font = core.getfont(
TypeError: argument 1 must be str, bytes or bytearray, not PosixPath
Funnily enough, the __init__ function of FreeTypeFont checks if the passed font argument is of type bytes, str or Path:
Line 215 in f9c7bd8
| if is_path(font): |
The problem occurs later when the
core object should load the font which presumably only works if font is a string:Lines 226 to 228 in f9c7bd8
| self.font = core.getfont( | |
| font, size, index, encoding, layout_engine=layout_engine | |
| ) |
This makes me think, that the ImageFont.truetype() function should indeed accept Path objects and internally convert the argument into a string before fowarding it to core.getfont().
What are your OS, Python and Pillow versions?
- OS: Ubuntu 22.04.3 LTS
- Python: 3.10.7
- Pillow: 10.1.0