1
from __future__ import annotations
5
from PIL import Image, ImagePalette
7
from .helper import assert_image_equal, assert_image_equal_tofile, hopper
10
def test_putpalette() -> None:
11
def palette(mode: str) -> str | tuple[str, list[int]]:
12
im = hopper(mode).copy()
13
im.putpalette(list(range(256)) * 3)
16
return im.mode, p[:10]
19
with pytest.raises(ValueError):
21
for mode in ["L", "LA", "P", "PA"]:
22
assert palette(mode) == (
23
"PA" if "A" in mode else "P",
24
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
26
with pytest.raises(ValueError):
28
with pytest.raises(ValueError):
30
with pytest.raises(ValueError):
32
with pytest.raises(ValueError):
34
with pytest.raises(ValueError):
37
with Image.open("Tests/images/hopper_gray.jpg") as im:
39
im.putpalette(list(range(256)) * 3)
41
with Image.open("Tests/images/la.tga") as im:
42
assert im.mode == "LA"
43
im.putpalette(list(range(256)) * 3)
46
def test_imagepalette() -> None:
48
im.putpalette(ImagePalette.negative())
49
assert_image_equal_tofile(im.convert("RGB"), "Tests/images/palette_negative.png")
51
im.putpalette(ImagePalette.random())
53
im.putpalette(ImagePalette.sepia())
54
assert_image_equal_tofile(im.convert("RGB"), "Tests/images/palette_sepia.png")
56
im.putpalette(ImagePalette.wedge())
57
assert_image_equal_tofile(im.convert("RGB"), "Tests/images/palette_wedge.png")
60
def test_putpalette_with_alpha_values() -> None:
61
with Image.open("Tests/images/transparent.gif") as im:
62
expected = im.convert("RGBA")
64
palette = im.getpalette()
65
transparency = im.info.pop("transparency")
67
palette_with_alpha_values = []
69
color = palette[i * 3 : i * 3 + 3]
70
alpha = 0 if i == transparency else 255
71
palette_with_alpha_values += color + [alpha]
72
im.putpalette(palette_with_alpha_values, "RGBA")
74
assert_image_equal(im.convert("RGBA"), expected)
77
@pytest.mark.parametrize(
80
("RGBA", (1, 2, 3, 4)),
81
("RGBAX", (1, 2, 3, 4, 0)),
82
("ARGB", (4, 1, 2, 3)),
85
def test_rgba_palette(mode: str, palette: tuple[int, ...]) -> None:
86
im = Image.new("P", (1, 1))
87
im.putpalette(palette, mode)
88
assert im.getpalette() == [1, 2, 3]
89
assert im.palette is not None
90
assert im.palette.colors == {(1, 2, 3, 4): 0}
93
def test_empty_palette() -> None:
94
im = Image.new("P", (1, 1))
95
assert im.getpalette() == []
98
def test_undefined_palette_index() -> None:
99
im = Image.new("P", (1, 1), 3)
100
im.putpalette((1, 2, 3))
101
assert im.convert("RGB").getpixel((0, 0)) == (0, 0, 0)