From b5160591bc9da2425ff15b632215139eafc2cce6 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 7 Jan 2022 16:29:38 +1100 Subject: [PATCH] Return an empty bytestring from tobytes() for an empty image --- Tests/test_image.py | 5 +++++ src/PIL/Image.py | 3 +++ 2 files changed, 8 insertions(+) diff --git a/Tests/test_image.py b/Tests/test_image.py index 4dde66f11..2d46d760d 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -786,6 +786,11 @@ class TestImage: 34665: 196, } + @pytest.mark.parametrize("size", ((1, 0), (0, 1), (0, 0))) + def test_zero_tobytes(self, size): + im = Image.new("RGB", size) + assert im.tobytes() == b"" + def test_categories_deprecation(self): with pytest.warns(DeprecationWarning): assert hopper().category == 0 diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 0bafd3907..69089a290 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -716,6 +716,9 @@ class Image: self.load() + if self.width == 0 or self.height == 0: + return b"" + # unpack data e = _getencoder(self.mode, encoder_name, args) e.setimage(self.im)