From 8784ee1410480b325e92fcf6d238e7a2de1589fb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 22 Jul 2022 07:59:30 +1000 Subject: [PATCH] Moved code into separate function --- src/PIL/ImageFile.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/PIL/ImageFile.py b/src/PIL/ImageFile.py index 99b77a37f5f..9f08493c13f 100644 --- a/src/PIL/ImageFile.py +++ b/src/PIL/ImageFile.py @@ -499,9 +499,14 @@ def _save(im, fp, tile, bufsize=0): try: fh = fp.fileno() fp.flush() - exc = None - except (AttributeError, io.UnsupportedOperation) as e: - exc = e + _encode_tile(im, fp, tile, bufsize, fh) + except (AttributeError, io.UnsupportedOperation) as exc: + _encode_tile(im, fp, tile, bufsize, None, exc) + if hasattr(fp, "flush"): + fp.flush() + + +def _encode_tile(im, fp, tile, bufsize, fh, exc=None): for e, b, o, a in tile: if o > 0: fp.seek(o) @@ -526,8 +531,6 @@ def _save(im, fp, tile, bufsize=0): raise OSError(f"encoder error {s} when writing image file") from exc finally: encoder.cleanup() - if hasattr(fp, "flush"): - fp.flush() def _safe_read(fp, size):