From 45b228e835c35b9ae19877402b5041410ed4dee3 Mon Sep 17 00:00:00 2001 From: Guillaume Ayoub Date: Mon, 3 Aug 2020 18:07:38 +0200 Subject: [PATCH 1/2] Fix exception handling when saving images The e variable is already used in the for loop, use exc to store the exception. --- src/PIL/ImageFile.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py index 81ec0c266..b06b89811 100644 --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -509,7 +509,7 @@ def _save(im, fp, tile, bufsize=0): try: fh = fp.fileno() fp.flush() - except (AttributeError, io.UnsupportedOperation) as e: + except (AttributeError, io.UnsupportedOperation) as exc: # compress to Python file-compatible object for e, b, o, a in tile: e = Image._getencoder(im.mode, e, a, im.encoderconfig) @@ -526,7 +526,7 @@ def _save(im, fp, tile, bufsize=0): if s: break if s < 0: - raise OSError("encoder error %d when writing image file" % s) from e + raise OSError("encoder error %d when writing image file" % s) from exc e.cleanup() else: # slight speedup: compress to real file object From 0af193afc0a66545667b651444256234f63ad1fe Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 4 Aug 2020 21:58:03 +1000 Subject: [PATCH 2/2] Added test --- Tests/test_imagefile.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Tests/test_imagefile.py b/Tests/test_imagefile.py index e0dbd909a..b4107e8e3 100644 --- a/Tests/test_imagefile.py +++ b/Tests/test_imagefile.py @@ -244,3 +244,8 @@ class TestPyDecoder: im = MockImageFile(buf) assert im.format is None assert im.get_format_mimetype() is None + + def test_oserror(self): + im = Image.new("RGB", (1, 1)) + with pytest.raises(OSError): + im.save(BytesIO(), "JPEG2000")