Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Tests/test_imagefont.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,11 @@ def test_stroke_mask() -> None:
assert mask.getpixel((42, 5)) == 255


def test_load_invalid_file() -> None:
with pytest.raises(SyntaxError, match="Not a PILfont file"):
ImageFont.load("Tests/images/1_trns.png")


def test_load_when_image_not_found() -> None:
with tempfile.NamedTemporaryFile(delete=False) as tmp:
pass
Expand Down
8 changes: 8 additions & 0 deletions Tests/test_imagefontpil.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ def test_default_font(font: ImageFont.ImageFont) -> None:
assert_image_equal_tofile(im, "Tests/images/default_font.png")


def test_invalid_mode() -> None:
font = ImageFont.ImageFont()
fp = BytesIO()
with Image.open("Tests/images/hopper.png") as im:
with pytest.raises(TypeError, match="invalid font image mode"):
font._load_pilfont_data(fp, im)


def test_without_freetype() -> None:
original_core = ImageFont.core
if features.check_module("freetype2"):
Expand Down
14 changes: 7 additions & 7 deletions src/PIL/ImageFont.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,16 @@ def _load_pilfont(self, filename: str) -> None:
image.close()

def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
# check image
if image.mode not in ("1", "L"):
msg = "invalid font image mode"
raise TypeError(msg)

# read PILfont header
if file.readline() != b"PILfont\n":
if file.read(8) != b"PILfont\n":
msg = "Not a PILfont file"
raise SyntaxError(msg)
file.readline().split(b";")
file.readline()
self.info = [] # FIXME: should be a dictionary
while True:
s = file.readline()
Expand All @@ -140,11 +145,6 @@ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
# read PILfont metrics
data = file.read(256 * 20)

# check image
if image.mode not in ("1", "L"):
msg = "invalid font image mode"
raise TypeError(msg)

image.load()

self.font = Image.core.font(image.im, data)
Expand Down
Loading