Raise mode error before reading

This commit is contained in:
Andrew Murray 2025-09-02 21:32:13 +10:00
parent 485d9884cf
commit caacd38e1b
2 changed files with 13 additions and 5 deletions

View File

@ -30,6 +30,14 @@ def test_default_font(font: ImageFont.ImageFont) -> None:
assert_image_equal_tofile(im, "Tests/images/default_font.png") 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: def test_without_freetype() -> None:
original_core = ImageFont.core original_core = ImageFont.core
if features.check_module("freetype2"): if features.check_module("freetype2"):

View File

@ -125,6 +125,11 @@ class ImageFont:
image.close() image.close()
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None: 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 # read PILfont header
if file.read(8) != b"PILfont\n": if file.read(8) != b"PILfont\n":
msg = "Not a PILfont file" msg = "Not a PILfont file"
@ -140,11 +145,6 @@ class ImageFont:
# read PILfont metrics # read PILfont metrics
data = file.read(256 * 20) data = file.read(256 * 20)
# check image
if image.mode not in ("1", "L"):
msg = "invalid font image mode"
raise TypeError(msg)
image.load() image.load()
self.font = Image.core.font(image.im, data) self.font = Image.core.font(image.im, data)