1
from __future__ import annotations
7
from .helper import assert_image_equal, hopper
10
@pytest.mark.parametrize("mode", ("1", "P", "L", "RGB", "I", "F"))
11
def test_crop(mode: str) -> None:
13
assert_image_equal(im.crop(), im)
15
cropped = im.crop((50, 50, 100, 100))
16
assert cropped.mode == mode
17
assert cropped.size == (50, 50)
20
def test_wide_crop() -> None:
21
def crop(bbox: tuple[int, int, int, int]) -> tuple[int, ...]:
24
while h and not h[-1]:
28
im = Image.new("L", (100, 100), 1)
30
assert crop((0, 0, 100, 100)) == (0, 10000)
31
assert crop((25, 25, 75, 75)) == (0, 2500)
34
assert crop((-25, 0, 25, 50)) == (1250, 1250)
35
assert crop((0, -25, 50, 25)) == (1250, 1250)
36
assert crop((75, 0, 125, 50)) == (1250, 1250)
37
assert crop((0, 75, 50, 125)) == (1250, 1250)
39
assert crop((-25, 25, 125, 75)) == (2500, 5000)
40
assert crop((25, -25, 75, 125)) == (2500, 5000)
43
assert crop((-25, -25, 25, 25)) == (1875, 625)
44
assert crop((75, -25, 125, 25)) == (1875, 625)
45
assert crop((75, 75, 125, 125)) == (1875, 625)
46
assert crop((-25, 75, 25, 125)) == (1875, 625)
49
@pytest.mark.parametrize("box", ((8, 2, 2, 8), (2, 8, 8, 2), (8, 8, 2, 2)))
50
def test_negative_crop(box: tuple[int, int, int, int]) -> None:
51
im = Image.new("RGB", (10, 10))
53
with pytest.raises(ValueError):
57
def test_crop_float() -> None:
58
# Check cropping floats are rounded to nearest integer
59
# https://github.com/python-pillow/Pillow/issues/1744
62
im = Image.new("RGB", (10, 10))
63
assert im.size == (10, 10)
66
cropped = im.crop((0.9, 1.1, 4.2, 5.8))
69
assert cropped.size == (3, 5)
72
def test_crop_crash() -> None:
73
# Image.crop crashes prepatch with an access violation
74
# apparently a use after free on Windows, see
75
# https://github.com/python-pillow/Pillow/issues/1077
77
test_img = "Tests/images/bmp/g/pal8-0.bmp"
78
extents = (1, 1, 10, 10)
80
with Image.open(test_img) as img:
81
img2 = img.crop(extents)
85
with Image.open(test_img) as img:
86
img = img.crop(extents)
90
def test_crop_zero() -> None:
91
im = Image.new("RGB", (0, 0), "white")
93
cropped = im.crop((0, 0, 0, 0))
94
assert cropped.size == (0, 0)
96
cropped = im.crop((10, 10, 20, 20))
97
assert cropped.size == (10, 10)
98
assert cropped.getdata()[0] == (0, 0, 0)
100
im = Image.new("RGB", (0, 0))
102
cropped = im.crop((10, 10, 20, 20))
103
assert cropped.size == (10, 10)
104
assert cropped.getdata()[2] == (0, 0, 0)