From a7537b1b06490ef3dfbf0bf1c48a0b8c9aa36940 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 30 Mar 2025 07:31:17 +1100 Subject: [PATCH] Only change readonly if saved filename matches opened filename --- Tests/test_image.py | 9 +++++++++ src/PIL/Image.py | 7 ++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index c2e850c36..7e6118d52 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -258,6 +258,15 @@ class TestImage: assert im.readonly im.save(temp_file) + def test_save_without_changing_readonly(self, tmp_path: Path) -> None: + temp_file = tmp_path / "temp.bmp" + + with Image.open("Tests/images/rgb32bf-rgba.bmp") as im: + assert im.readonly + + im.save(temp_file) + assert im.readonly + def test_dump(self, tmp_path: Path) -> None: im = Image.new("L", (10, 10)) im._dump(str(tmp_path / "temp_L.ppm")) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 233df592c..c62d7a8a3 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2540,8 +2540,13 @@ class Image: msg = f"unknown file extension: {ext}" raise ValueError(msg) from e + from . import ImageFile + # may mutate self! - self._ensure_mutable() + if isinstance(self, ImageFile.ImageFile) and filename == self.filename: + self._ensure_mutable() + else: + self.load() save_all = params.pop("save_all", None) self.encoderinfo = {**getattr(self, "encoderinfo", {}), **params}