Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle truncated chunks at the end of PNG images #7709

Merged
merged 7 commits into from Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Binary file added Tests/images/truncated_end_chunk.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions Tests/test_file_png.py
Expand Up @@ -778,6 +778,18 @@ class MyStdOut:
with Image.open(mystdout) as reloaded:
assert_image_equal_tofile(reloaded, TEST_PNG_FILE)

def test_truncated_end_chunk(self):
lajiyuan marked this conversation as resolved.
Show resolved Hide resolved
with Image.open("Tests/images/truncated_end_chunk.png") as im:
with pytest.raises(OSError):
im.load()

ImageFile.LOAD_TRUNCATED_IMAGES = True
try:
with Image.open("Tests/images/truncated_end_chunk.png") as im:
assert_image_equal_tofile(im, "Tests/images/hopper.png")
finally:
ImageFile.LOAD_TRUNCATED_IMAGES = False


@pytest.mark.skipif(is_win32(), reason="Requires Unix or macOS")
@skip_unless_feature("zlib")
Expand Down
8 changes: 7 additions & 1 deletion src/PIL/PngImagePlugin.py
Expand Up @@ -981,7 +981,13 @@
except EOFError:
if cid == b"fdAT":
length -= 4
ImageFile._safe_read(self.fp, length)
try:
ImageFile._safe_read(self.fp, length)
except OSError as e:
if ImageFile.LOAD_TRUNCATED_IMAGES:
break

Check warning on line 988 in src/PIL/PngImagePlugin.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/PngImagePlugin.py#L984-L988

Added lines #L984 - L988 were not covered by tests
else:
raise e

Check warning on line 990 in src/PIL/PngImagePlugin.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/PngImagePlugin.py#L990

Added line #L990 was not covered by tests
except AttributeError:
logger.debug("%r %s %s (unknown)", cid, pos, length)
s = ImageFile._safe_read(self.fp, length)
Expand Down