diff --git a/Tests/test_image.py b/Tests/test_image.py index afc6e8e166b..b4d380baf6a 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -263,6 +263,15 @@ def test_save_without_changing_readonly(self, tmp_path: Path) -> None: im.save(temp_file) assert im.readonly + @pytest.mark.parametrize("size", ((0, 1), (1, 0), (0, 0))) + def test_save_zero_dimension(self, tmp_path: Path, size: tuple[int, int]) -> None: + im = Image.new("RGB", size) + msg = "cannot save image with zero width or height" + with pytest.raises(ValueError, match=msg): + im.save(tmp_path / "test.png") + with pytest.raises(ValueError, match=msg): + im.save(tmp_path / "test.gif") + 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 eb561611718..d72281ec061 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2517,10 +2517,15 @@ def save( :returns: None :exception ValueError: If the output format could not be determined from the file name. Use the format option to solve this. + :exception ValueError: If the image has zero width or height. :exception OSError: If the file could not be written. The file may have been created, and may contain partial data. """ + if self.size[0] <= 0 or self.size[1] <= 0: + msg = f"cannot save image with zero width or height (size: {self.size})" + raise ValueError(msg) + filename: str | bytes = "" open_fp = False if is_path(fp):