Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise an error when performing a negative crop #5972

Merged
merged 2 commits into from
Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 4 additions & 13 deletions Tests/test_decompression_bomb.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,21 +86,12 @@ def testEnlargeCrop(self):
pytest.warns(Image.DecompressionBombWarning, src.crop, box)

def test_crop_decompression_checks(self):

im = Image.new("RGB", (100, 100))

good_values = ((-9999, -9999, -9990, -9990), (-999, -999, -990, -990))

warning_values = ((-160, -160, 99, 99), (160, 160, -99, -99))

error_values = ((-99909, -99990, 99999, 99999), (99909, 99990, -99999, -99999))

for value in good_values:
for value in ((-9999, -9999, -9990, -9990), (-999, -999, -990, -990)):
assert im.crop(value).size == (9, 9)

for value in warning_values:
pytest.warns(Image.DecompressionBombWarning, im.crop, value)
pytest.warns(Image.DecompressionBombWarning, im.crop, (-160, -160, 99, 99))

for value in error_values:
with pytest.raises(Image.DecompressionBombError):
im.crop(value)
with pytest.raises(Image.DecompressionBombError):
im.crop((-99909, -99990, 99999, 99999))
14 changes: 5 additions & 9 deletions Tests/test_image_crop.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,12 @@ def crop(*bbox):
assert crop(-25, 75, 25, 125) == (1875, 625)


def test_negative_crop():
# Check negative crop size (@PIL171)

im = Image.new("L", (512, 512))
im = im.crop((400, 400, 200, 200))
@pytest.mark.parametrize("box", ((8, 2, 2, 8), (2, 8, 8, 2), (8, 8, 2, 2)))
def test_negative_crop(box):
im = Image.new("RGB", (10, 10))

assert im.size == (0, 0)
assert len(im.getdata()) == 0
with pytest.raises(IndexError):
im.getdata()[0]
with pytest.raises(ValueError):
im.crop(box)


def test_crop_float():
Expand Down
5 changes: 5 additions & 0 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,11 @@ def crop(self, box=None):
if box is None:
return self.copy()

if box[2] < box[0]:
raise ValueError("Region right less than region left")
elif box[3] < box[1]:
raise ValueError("Region lower less than region upper")
radarhere marked this conversation as resolved.
Show resolved Hide resolved

self.load()
return self._new(self._crop(self.im, box))

Expand Down