Removed duplicate code

This commit is contained in:
Andrew Murray 2022-02-28 13:59:52 +11:00
parent 4d868abd8a
commit bb9338e34d

View File

@ -499,44 +499,33 @@ def _save(im, fp, tile, bufsize=0):
try: try:
fh = fp.fileno() fh = fp.fileno()
fp.flush() fp.flush()
except (AttributeError, io.UnsupportedOperation) as exc: exc = None
# compress to Python file-compatible object except (AttributeError, io.UnsupportedOperation) as e:
exc = e
for e, b, o, a in tile: for e, b, o, a in tile:
if o > 0: if o > 0:
fp.seek(o) fp.seek(o)
e = Image._getencoder(im.mode, e, a, im.encoderconfig) encoder = Image._getencoder(im.mode, e, a, im.encoderconfig)
try: try:
e.setimage(im.im, b) encoder.setimage(im.im, b)
if e.pushes_fd: if encoder.pushes_fd:
e.setfd(fp) encoder.setfd(fp)
l, s = e.encode_to_pyfd() l, s = encoder.encode_to_pyfd()
else: else:
if exc:
# compress to Python file-compatible object
while True: while True:
l, s, d = e.encode(bufsize) l, s, d = encoder.encode(bufsize)
fp.write(d) fp.write(d)
if s: if s:
break break
else:
# slight speedup: compress to real file object
s = encoder.encode_to_file(fh, bufsize)
if s < 0: if s < 0:
raise OSError(f"encoder error {s} when writing image file") from exc raise OSError(f"encoder error {s} when writing image file") from exc
finally: finally:
e.cleanup() encoder.cleanup()
else:
# slight speedup: compress to real file object
for e, b, o, a in tile:
if o > 0:
fp.seek(o)
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
try:
e.setimage(im.im, b)
if e.pushes_fd:
e.setfd(fp)
l, s = e.encode_to_pyfd()
else:
s = e.encode_to_file(fh, bufsize)
if s < 0:
raise OSError(f"encoder error {s} when writing image file")
finally:
e.cleanup()
if hasattr(fp, "flush"): if hasattr(fp, "flush"):
fp.flush() fp.flush()