Skip to content

Commit 00a5426

Browse files
authored
Catch KeyError when checking mode from PNG IHDR chunk (#9604)
2 parents a4cbe9d + 408cec4 commit 00a5426

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

Tests/test_file_png.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,14 @@ def test_broken(self) -> None:
124124
with Image.open(test_file):
125125
pass
126126

127+
def test_ihdr_unknown_mode(self) -> None:
128+
fp = BytesIO(chunk(b"IHDR", b"\x00" * 13))
129+
with PngImagePlugin.PngStream(fp) as png:
130+
cid, pos, length = png.read()
131+
png.call(cid, pos, length)
132+
133+
assert png.im_mode == ""
134+
127135
def test_bad_text(self) -> None:
128136
# Make sure PIL can read malformed tEXt chunks (@PIL152)
129137

src/PIL/PngImagePlugin.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,9 @@ def __init__(self, fp: IO[bytes]) -> None:
400400

401401
self.text_memory = 0
402402

403+
def __enter__(self) -> PngStream:
404+
return self
405+
403406
def check_text_memory(self, chunklen: int) -> None:
404407
self.text_memory += chunklen
405408
if self.text_memory > MAX_TEXT_MEMORY:
@@ -461,7 +464,7 @@ def chunk_IHDR(self, pos: int, length: int) -> bytes:
461464
self.im_size = i32(s, 0), i32(s, 4)
462465
try:
463466
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
464-
except Exception:
467+
except KeyError:
465468
pass
466469
if s[12]:
467470
self.im_info["interlace"] = 1

0 commit comments

Comments
 (0)