Do not write new image to disk until it is successfully completed

This commit is contained in:
Andrew Murray 2022-01-10 11:58:22 +11:00
parent eff6c34bd1
commit 2f568643f0
2 changed files with 16 additions and 0 deletions

View File

@ -641,6 +641,15 @@ class TestImage:
im.save(temp_file)
assert not record
def test_no_new_file_on_error(self, tmp_path):
temp_file = str(tmp_path / "temp.jpg")
im = Image.new("RGB", (0, 0))
with pytest.raises(SystemError):
im.save(temp_file)
assert not os.path.exists(temp_file)
def test_load_on_nonexclusive_multiframe(self):
with open("Tests/images/frozenpond.mpo", "rb") as fp:

View File

@ -2202,16 +2202,23 @@ class Image:
else:
save_handler = SAVE[format.upper()]
new_file = False
if open_fp:
if params.get("append", False):
# Open also for reading ("+"), because TIFF save_all
# writer needs to go back and edit the written data.
fp = builtins.open(filename, "r+b")
elif not os.path.exists(filename):
new_file = True
fp = io.BytesIO()
else:
fp = builtins.open(filename, "w+b")
try:
save_handler(self, fp, filename)
if new_file:
with builtins.open(filename, "w+b") as new_file_fp:
new_file_fp.write(fp.getvalue())
finally:
# do what we can to clean up
if open_fp: