Skip to content

Commit a20abff

Browse files
authored
Merge pull request #7709 from lajiyuan/main
Handle truncated chunks at the end of PNG images
2 parents 1f60243 + 58554de commit a20abff

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed
29.6 KB
Loading

Tests/test_file_png.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,18 @@ class MyStdOut:
783783
with Image.open(mystdout) as reloaded:
784784
assert_image_equal_tofile(reloaded, TEST_PNG_FILE)
785785

786+
def test_truncated_end_chunk(self) -> None:
787+
with Image.open("Tests/images/truncated_end_chunk.png") as im:
788+
with pytest.raises(OSError):
789+
im.load()
790+
791+
ImageFile.LOAD_TRUNCATED_IMAGES = True
792+
try:
793+
with Image.open("Tests/images/truncated_end_chunk.png") as im:
794+
assert_image_equal_tofile(im, "Tests/images/hopper.png")
795+
finally:
796+
ImageFile.LOAD_TRUNCATED_IMAGES = False
797+
786798

787799
@pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS")
788800
@skip_unless_feature("zlib")

src/PIL/PngImagePlugin.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -981,7 +981,13 @@ def load_end(self):
981981
except EOFError:
982982
if cid == b"fdAT":
983983
length -= 4
984-
ImageFile._safe_read(self.fp, length)
984+
try:
985+
ImageFile._safe_read(self.fp, length)
986+
except OSError as e:
987+
if ImageFile.LOAD_TRUNCATED_IMAGES:
988+
break
989+
else:
990+
raise e
985991
except AttributeError:
986992
logger.debug("%r %s %s (unknown)", cid, pos, length)
987993
s = ImageFile._safe_read(self.fp, length)

0 commit comments

Comments
 (0)