Skip to content

Commit bb9338e

Browse files
committed
Removed duplicate code
1 parent 4d868ab commit bb9338e

File tree

1 file changed

+22
-33
lines changed

1 file changed

+22
-33
lines changed

src/PIL/ImageFile.py

Lines changed: 22 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -499,44 +499,33 @@ def _save(im, fp, tile, bufsize=0):
499499
try:
500500
fh = fp.fileno()
501501
fp.flush()
502-
except (AttributeError, io.UnsupportedOperation) as exc:
503-
# compress to Python file-compatible object
504-
for e, b, o, a in tile:
505-
if o > 0:
506-
fp.seek(o)
507-
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
508-
try:
509-
e.setimage(im.im, b)
510-
if e.pushes_fd:
511-
e.setfd(fp)
512-
l, s = e.encode_to_pyfd()
513-
else:
502+
exc = None
503+
except (AttributeError, io.UnsupportedOperation) as e:
504+
exc = e
505+
for e, b, o, a in tile:
506+
if o > 0:
507+
fp.seek(o)
508+
encoder = Image._getencoder(im.mode, e, a, im.encoderconfig)
509+
try:
510+
encoder.setimage(im.im, b)
511+
if encoder.pushes_fd:
512+
encoder.setfd(fp)
513+
l, s = encoder.encode_to_pyfd()
514+
else:
515+
if exc:
516+
# compress to Python file-compatible object
514517
while True:
515-
l, s, d = e.encode(bufsize)
518+
l, s, d = encoder.encode(bufsize)
516519
fp.write(d)
517520
if s:
518521
break
519-
if s < 0:
520-
raise OSError(f"encoder error {s} when writing image file") from exc
521-
finally:
522-
e.cleanup()
523-
else:
524-
# slight speedup: compress to real file object
525-
for e, b, o, a in tile:
526-
if o > 0:
527-
fp.seek(o)
528-
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
529-
try:
530-
e.setimage(im.im, b)
531-
if e.pushes_fd:
532-
e.setfd(fp)
533-
l, s = e.encode_to_pyfd()
534522
else:
535-
s = e.encode_to_file(fh, bufsize)
536-
if s < 0:
537-
raise OSError(f"encoder error {s} when writing image file")
538-
finally:
539-
e.cleanup()
523+
# slight speedup: compress to real file object
524+
s = encoder.encode_to_file(fh, bufsize)
525+
if s < 0:
526+
raise OSError(f"encoder error {s} when writing image file") from exc
527+
finally:
528+
encoder.cleanup()
540529
if hasattr(fp, "flush"):
541530
fp.flush()
542531

0 commit comments

Comments
 (0)