Pillow

Форк
0
/
test_imagepalette.py 
200 строк · 5.0 Кб
1
from __future__ import annotations
2

3
from pathlib import Path
4

5
import pytest
6

7
from PIL import Image, ImagePalette
8

9
from .helper import assert_image_equal, assert_image_equal_tofile
10

11

12
def test_sanity() -> None:
13
    palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
14
    assert len(palette.colors) == 256
15

16

17
def test_reload() -> None:
18
    with Image.open("Tests/images/hopper.gif") as im:
19
        original = im.copy()
20
        im.palette.dirty = 1
21
        assert_image_equal(im.convert("RGB"), original.convert("RGB"))
22

23

24
def test_getcolor() -> None:
25
    palette = ImagePalette.ImagePalette()
26
    assert len(palette.palette) == 0
27
    assert len(palette.colors) == 0
28

29
    test_map = {}
30
    for i in range(256):
31
        test_map[palette.getcolor((i, i, i))] = i
32
    assert len(test_map) == 256
33

34
    # Colors can be converted between RGB and RGBA
35
    rgba_palette = ImagePalette.ImagePalette("RGBA")
36
    assert rgba_palette.getcolor((0, 0, 0)) == rgba_palette.getcolor((0, 0, 0, 255))
37

38
    assert palette.getcolor((0, 0, 0)) == palette.getcolor((0, 0, 0, 255))
39

40
    # An error is raised when the palette is full
41
    with pytest.raises(ValueError):
42
        palette.getcolor((1, 2, 3))
43
    # But not if the image is not using one of the palette entries
44
    palette.getcolor((1, 2, 3), image=Image.new("P", (1, 1)))
45

46
    # Test unknown color specifier
47
    with pytest.raises(ValueError):
48
        palette.getcolor("unknown")  # type: ignore[arg-type]
49

50

51
def test_getcolor_rgba_color_rgb_palette() -> None:
52
    palette = ImagePalette.ImagePalette("RGB")
53

54
    # Opaque RGBA colors are converted
55
    assert palette.getcolor((0, 0, 0, 255)) == palette.getcolor((0, 0, 0))
56

57
    with pytest.raises(ValueError):
58
        palette.getcolor((0, 0, 0, 128))
59

60

61
@pytest.mark.parametrize(
62
    "index, palette",
63
    [
64
        # Test when the palette is not full
65
        (0, ImagePalette.ImagePalette()),
66
        # Test when the palette is full
67
        (255, ImagePalette.ImagePalette("RGB", list(range(256)) * 3)),
68
    ],
69
)
70
def test_getcolor_not_special(index: int, palette: ImagePalette.ImagePalette) -> None:
71
    im = Image.new("P", (1, 1))
72

73
    # Do not use transparency index as a new color
74
    im.info["transparency"] = index
75
    index1 = palette.getcolor((0, 0, 0), im)
76
    assert index1 != index
77

78
    # Do not use background index as a new color
79
    im.info["background"] = index1
80
    index2 = palette.getcolor((0, 0, 1), im)
81
    assert index2 not in (index, index1)
82

83

84
def test_file(tmp_path: Path) -> None:
85
    palette = ImagePalette.ImagePalette("RGB", list(range(256)) * 3)
86

87
    f = str(tmp_path / "temp.lut")
88

89
    palette.save(f)
90

91
    lut = ImagePalette.load(f)
92

93
    # load returns raw palette information
94
    assert len(lut[0]) == 768
95
    assert lut[1] == "RGB"
96

97
    p = ImagePalette.raw(lut[1], lut[0])
98
    assert isinstance(p, ImagePalette.ImagePalette)
99
    assert p.palette == palette.tobytes()
100

101

102
def test_make_linear_lut() -> None:
103
    # Arrange
104
    black = 0
105
    white = 255
106

107
    # Act
108
    lut = ImagePalette.make_linear_lut(black, white)
109

110
    # Assert
111
    assert isinstance(lut, list)
112
    assert len(lut) == 256
113
    # Check values
114
    for i in range(0, len(lut)):
115
        assert lut[i] == i
116

117

118
def test_make_linear_lut_not_yet_implemented() -> None:
119
    # Update after FIXME
120
    # Arrange
121
    black = 1
122
    white = 255
123

124
    # Act
125
    with pytest.raises(NotImplementedError):
126
        ImagePalette.make_linear_lut(black, white)
127

128

129
def test_make_gamma_lut() -> None:
130
    # Arrange
131
    exp = 5
132

133
    # Act
134
    lut = ImagePalette.make_gamma_lut(exp)
135

136
    # Assert
137
    assert isinstance(lut, list)
138
    assert len(lut) == 256
139
    # Check a few values
140
    assert lut[0] == 0
141
    assert lut[63] == 0
142
    assert lut[127] == 8
143
    assert lut[191] == 60
144
    assert lut[255] == 255
145

146

147
def test_rawmode_valueerrors(tmp_path: Path) -> None:
148
    # Arrange
149
    palette = ImagePalette.raw("RGB", list(range(256)) * 3)
150

151
    # Act / Assert
152
    with pytest.raises(ValueError):
153
        palette.tobytes()
154
    with pytest.raises(ValueError):
155
        palette.getcolor((1, 2, 3))
156
    f = str(tmp_path / "temp.lut")
157
    with pytest.raises(ValueError):
158
        palette.save(f)
159

160

161
def test_getdata() -> None:
162
    # Arrange
163
    data_in = list(range(256)) * 3
164
    palette = ImagePalette.ImagePalette("RGB", data_in)
165

166
    # Act
167
    mode, data_out = palette.getdata()
168

169
    # Assert
170
    assert mode == "RGB"
171

172

173
def test_rawmode_getdata() -> None:
174
    # Arrange
175
    data_in = list(range(256)) * 3
176
    palette = ImagePalette.raw("RGB", data_in)
177

178
    # Act
179
    rawmode, data_out = palette.getdata()
180

181
    # Assert
182
    assert rawmode == "RGB"
183
    assert data_in == data_out
184

185

186
def test_2bit_palette(tmp_path: Path) -> None:
187
    # issue #2258, 2 bit palettes are corrupted.
188
    outfile = str(tmp_path / "temp.png")
189

190
    rgb = b"\x00" * 2 + b"\x01" * 2 + b"\x02" * 2
191
    img = Image.frombytes("P", (6, 1), rgb)
192
    img.putpalette(b"\xFF\x00\x00\x00\xFF\x00\x00\x00\xFF")  # RGB
193
    img.save(outfile, format="PNG")
194

195
    assert_image_equal_tofile(img, outfile)
196

197

198
def test_invalid_palette() -> None:
199
    with pytest.raises(OSError):
200
        ImagePalette.load("Tests/images/hopper.jpg")
201

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.