Skip to content

Commit

Permalink
Merge pull request #5921 from radarhere/jpeg_eoi
Browse files Browse the repository at this point in the history
Ensure JpegImagePlugin stops at the end of a truncated file
  • Loading branch information
mergify[bot] authored Jan 1, 2022
2 parents 525c840 + 1059eb5 commit baae9ec
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
24 changes: 24 additions & 0 deletions Tests/test_file_jpeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,30 @@ def test_getxmp(self):
with Image.open("Tests/images/hopper.jpg") as im:
assert im.getxmp() == {}

@pytest.mark.timeout(timeout=1)
def test_eof(self):
# Even though this decoder never says that it is finished
# the image should still end when there is no new data
class InfiniteMockPyDecoder(ImageFile.PyDecoder):
def decode(self, buffer):
return 0, 0

decoder = InfiniteMockPyDecoder(None)

def closure(mode, *args):
decoder.__init__(mode, *args)
return decoder

Image.register_decoder("INFINITE", closure)

with Image.open(TEST_FILE) as im:
im.tile = [
("INFINITE", (0, 0, 128, 128), 0, ("RGB", 0, 1)),
]
ImageFile.LOAD_TRUNCATED_IMAGES = True
im.load()
ImageFile.LOAD_TRUNCATED_IMAGES = False


@pytest.mark.skipif(not is_win32(), reason="Windows only")
@skip_unless_feature("jpg")
Expand Down
3 changes: 2 additions & 1 deletion src/PIL/JpegImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,10 @@ def load_read(self, read_bytes):
"""
s = self.fp.read(read_bytes)

if not s and ImageFile.LOAD_TRUNCATED_IMAGES:
if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
# Premature EOF.
# Pretend file is finished adding EOI marker
self._ended = True
return b"\xFF\xD9"

return s
Expand Down

0 comments on commit baae9ec

Please sign in to comment.