diff --git a/PIL/Image.py b/PIL/Image.py index f20640c19..bbfee34b6 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1985,6 +1985,22 @@ def _wedge(): return Image()._new(core.wedge("L")) +def _check_size(size): + """ + Common check to enforce type and sanity check on size tuples + + :param size: Should be a 2 tuple of (width, height) + :returns: True, or raises a ValueError + """ + + if not isinstance(size, tuple): + raise ValueError("Size must be a tuple") + if len(size) != 2: + raise ValueError("Size must be a tuple of length 2") + if size[0] <= 0 or size[1] <= 0: + raise ValueError("Width and Height must be > 0") + + return True def new(mode, size, color=0): """ @@ -2002,6 +2018,8 @@ def new(mode, size, color=0): :returns: An :py:class:`~PIL.Image.Image` object. """ + _check_size(size) + if color is None: # don't initialize return Image()._new(core.new(mode, size)) @@ -2039,6 +2057,8 @@ def frombytes(mode, size, data, decoder_name="raw", *args): :returns: An :py:class:`~PIL.Image.Image` object. """ + _check_size(size) + # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] @@ -2091,6 +2111,8 @@ def frombuffer(mode, size, data, decoder_name="raw", *args): .. versionadded:: 1.1.4 """ + _check_size(size) + # may pass tuple instead of argument list if len(args) == 1 and isinstance(args[0], tuple): args = args[0] diff --git a/Tests/test_image.py b/Tests/test_image.py index b3fbd508d..1a67d79c8 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -237,5 +237,17 @@ class TestImage(PillowTestCase): im3 = Image.open('Tests/images/effect_spread.png') self.assert_image_similar(im2, im3, 110) + def test_check_size(self): + # Checking that the _check_size function throws value errors when we want it to. + with self.assertRaises(ValueError): + Image.new('RGB', 0) # not a tuple + with self.assertRaises(ValueError): + Image.new('RGB', (0,)) # Tuple too short + with self.assertRaises(ValueError): + Image.new('RGB', (0,0)) # w,h <= 0 + + self.assertTrue(Image.new('RGB', (1,1))) + + if __name__ == '__main__': unittest.main()