Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ImageFont.truetype() function does not accept Path objects #7577

Closed
MauroPfister opened this issue Nov 27, 2023 · 2 comments · Fixed by #7578
Closed

ImageFont.truetype() function does not accept Path objects #7577

MauroPfister opened this issue Nov 27, 2023 · 2 comments · Fixed by #7578
Labels

Comments

@MauroPfister
Copy link

MauroPfister commented Nov 27, 2023

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:

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:

Pillow/src/PIL/ImageFont.py

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
@radarhere
Copy link
Member

I've created PR #7578 to resolve this.

@MauroPfister
Copy link
Author

Wow, that was fast. Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants