🌐 AI搜索 & 代理 主页
Skip to content

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

@MauroPfister

Description

@MauroPfister

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions