Skip to content

Commit 445451c

Browse files
committed
Added common check for size tuple errors
1 parent 1a43da7 commit 445451c

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

PIL/Image.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1985,6 +1985,22 @@ def _wedge():
19851985

19861986
return Image()._new(core.wedge("L"))
19871987

1988+
def _check_size(size):
1989+
"""
1990+
Common check to enforce type and sanity check on size tuples
1991+
1992+
:param size: Should be a 2 tuple of (width, height)
1993+
:returns: True, or raises a ValueError
1994+
"""
1995+
1996+
if not isinstance(size, tuple):
1997+
raise ValueError("Size must be a tuple")
1998+
if len(size) != 2:
1999+
raise ValueError("Size must be a tuple of length 2")
2000+
if size[0] <= 0 or size[1] <= 0:
2001+
raise ValueError("Width and Height must be > 0")
2002+
2003+
return True
19882004

19892005
def new(mode, size, color=0):
19902006
"""
@@ -2002,6 +2018,8 @@ def new(mode, size, color=0):
20022018
:returns: An :py:class:`~PIL.Image.Image` object.
20032019
"""
20042020

2021+
_check_size(size)
2022+
20052023
if color is None:
20062024
# don't initialize
20072025
return Image()._new(core.new(mode, size))
@@ -2039,6 +2057,8 @@ def frombytes(mode, size, data, decoder_name="raw", *args):
20392057
:returns: An :py:class:`~PIL.Image.Image` object.
20402058
"""
20412059

2060+
_check_size(size)
2061+
20422062
# may pass tuple instead of argument list
20432063
if len(args) == 1 and isinstance(args[0], tuple):
20442064
args = args[0]
@@ -2091,6 +2111,8 @@ def frombuffer(mode, size, data, decoder_name="raw", *args):
20912111
.. versionadded:: 1.1.4
20922112
"""
20932113

2114+
_check_size(size)
2115+
20942116
# may pass tuple instead of argument list
20952117
if len(args) == 1 and isinstance(args[0], tuple):
20962118
args = args[0]

Tests/test_image.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,5 +237,17 @@ def test_effect_spread(self):
237237
im3 = Image.open('Tests/images/effect_spread.png')
238238
self.assert_image_similar(im2, im3, 110)
239239

240+
def test_check_size(self):
241+
# Checking that the _check_size function throws value errors when we want it to.
242+
with self.assertRaises(ValueError):
243+
Image.new('RGB', 0) # not a tuple
244+
with self.assertRaises(ValueError):
245+
Image.new('RGB', (0,)) # Tuple too short
246+
with self.assertRaises(ValueError):
247+
Image.new('RGB', (0,0)) # w,h <= 0
248+
249+
self.assertTrue(Image.new('RGB', (1,1)))
250+
251+
240252
if __name__ == '__main__':
241253
unittest.main()

0 commit comments

Comments
 (0)