From caacd38e1be189ed5a9d9ba892e595cbdfaa551b Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 2 Sep 2025 21:32:13 +1000 Subject: [PATCH] Raise mode error before reading --- Tests/test_imagefontpil.py | 8 ++++++++ src/PIL/ImageFont.py | 10 +++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Tests/test_imagefontpil.py b/Tests/test_imagefontpil.py index 3eb98d379..8c1cb3f58 100644 --- a/Tests/test_imagefontpil.py +++ b/Tests/test_imagefontpil.py @@ -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"): diff --git a/src/PIL/ImageFont.py b/src/PIL/ImageFont.py index df2f00882..92eb763a5 100644 --- a/src/PIL/ImageFont.py +++ b/src/PIL/ImageFont.py @@ -125,6 +125,11 @@ class ImageFont: 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.read(8) != b"PILfont\n": msg = "Not a PILfont file" @@ -140,11 +145,6 @@ class ImageFont: # 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)