Skip to content

Commit caacd38

Browse files
committed
Raise mode error before reading
1 parent 485d988 commit caacd38

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

Tests/test_imagefontpil.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ def test_default_font(font: ImageFont.ImageFont) -> None:
3030
assert_image_equal_tofile(im, "Tests/images/default_font.png")
3131

3232

33+
def test_invalid_mode() -> None:
34+
font = ImageFont.ImageFont()
35+
fp = BytesIO()
36+
with Image.open("Tests/images/hopper.png") as im:
37+
with pytest.raises(TypeError, match="invalid font image mode"):
38+
font._load_pilfont_data(fp, im)
39+
40+
3341
def test_without_freetype() -> None:
3442
original_core = ImageFont.core
3543
if features.check_module("freetype2"):

src/PIL/ImageFont.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,11 @@ def _load_pilfont(self, filename: str) -> None:
125125
image.close()
126126

127127
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
128+
# check image
129+
if image.mode not in ("1", "L"):
130+
msg = "invalid font image mode"
131+
raise TypeError(msg)
132+
128133
# read PILfont header
129134
if file.read(8) != b"PILfont\n":
130135
msg = "Not a PILfont file"
@@ -140,11 +145,6 @@ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
140145
# read PILfont metrics
141146
data = file.read(256 * 20)
142147

143-
# check image
144-
if image.mode not in ("1", "L"):
145-
msg = "invalid font image mode"
146-
raise TypeError(msg)
147-
148148
image.load()
149149

150150
self.font = Image.core.font(image.im, data)

0 commit comments

Comments
 (0)