From 22b0110f89086b4d2dda3da81bce4eafab7746da Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 12 Mar 2019 08:54:43 +1100 Subject: [PATCH 1/2] Only close original fp in __del__ and __exit__ if original fp is exclusive --- Tests/test_image.py | 12 ++++++++++++ src/PIL/Image.py | 9 +++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index 330048057..19e64d746 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -532,6 +532,18 @@ class TestImage(PillowTestCase): with Image.open(test_file) as im: self.assert_warning(None, im.save, temp_file) + def test_load_on_nonexclusive_multiframe(self): + with open("Tests/images/frozenpond.mpo", "rb") as fp: + def act(fp): + im = Image.open(fp) + im.load() + act(fp) + + with Image.open(fp) as im: + im.load() + + self.assertFalse(fp.closed) + class MockEncoder(object): pass diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 51d6e8466..b690006b5 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -578,11 +578,12 @@ class Image(object): return self def __exit__(self, *args): - if hasattr(self, "_close__fp"): - self._close__fp() if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') - and self.fp and self._exclusive_fp): - self.fp.close() + and self._exclusive_fp): + if hasattr(self, "_close__fp"): + self._close__fp() + if self.fp: + self.fp.close() self.fp = None def close(self): From 9bdab56689da6db1b5b00297372d300fe9a84d69 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 18 Mar 2019 09:15:37 +1100 Subject: [PATCH 2/2] Replaced hasattr conditions with getattr and default --- src/PIL/Image.py | 3 +-- src/PIL/WebPImagePlugin.py | 7 ++----- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index b690006b5..e34c25487 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -578,8 +578,7 @@ class Image(object): return self def __exit__(self, *args): - if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') - and self._exclusive_fp): + if hasattr(self, 'fp') and getattr(self, '_exclusive_fp', False): if hasattr(self, "_close__fp"): self._close__fp() if self.fp: diff --git a/src/PIL/WebPImagePlugin.py b/src/PIL/WebPImagePlugin.py index 212e6b4c7..25557326b 100644 --- a/src/PIL/WebPImagePlugin.py +++ b/src/PIL/WebPImagePlugin.py @@ -186,7 +186,7 @@ def _save_all(im, fp, filename): # will preserve non-alpha modes total = 0 for ims in [im]+append_images: - total += 1 if not hasattr(ims, "n_frames") else ims.n_frames + total += getattr(ims, "n_frames", 1) if total == 1: _save(im, fp, filename) return @@ -254,10 +254,7 @@ def _save_all(im, fp, filename): try: for ims in [im]+append_images: # Get # of frames in this image - if not hasattr(ims, "n_frames"): - nfr = 1 - else: - nfr = ims.n_frames + nfr = getattr(ims, "n_frames", 1) for idx in range(nfr): ims.seek(idx)