diff --git a/Tests/test_image.py b/Tests/test_image.py index 1406fd6a35a..44bedef8bb6 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -220,6 +220,21 @@ def test_unknown_extension(self, tmp_path: Path) -> None: with pytest.raises(ValueError): im.save(temp_file) + def test_failed_save_does_not_affect_next_save(self, tmp_path: Path) -> None: + im = Image.new("RGB", (1, 1)) + with pytest.raises(KeyError): + im.save(io.BytesIO(), "UNKNOWN", dpi=(72, 72)) + with pytest.raises(KeyError): + im.save(io.BytesIO(), "BMP", save_all=True, dpi=(72, 72)) + with pytest.raises(FileNotFoundError): + im.save(tmp_path / "missing" / "temp.bmp", dpi=(72, 72)) + assert not hasattr(im, "encoderinfo") + + f = tmp_path / "temp.bmp" + im.save(f, dpi=(300, 300)) + with Image.open(f) as reloaded: + assert reloaded.info["dpi"] == pytest.approx((300, 300), abs=0.001) + def test_internals(self) -> None: im = Image.new("L", (100, 100)) im.readonly = 1 diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 26284b8dde5..c5c1b27f3fb 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2749,10 +2749,6 @@ def save( self.load() save_all = params.pop("save_all", None) - self._default_encoderinfo = params - encoderinfo = getattr(self, "encoderinfo", {}) - self._attach_default_encoderinfo(self) - self.encoderconfig: tuple[Any, ...] = () if format.upper() not in SAVE: init() @@ -2777,6 +2773,10 @@ def save( else: fp = cast("IO[bytes]", fp) + self._default_encoderinfo = params + encoderinfo = getattr(self, "encoderinfo", {}) + self._attach_default_encoderinfo(self) + self.encoderconfig: tuple[Any, ...] = () try: save_handler(self, fp, filename) except Exception: