Skip to content

Commit 25653d2

Browse files
authored
Corrected P mode save (#8685)
1 parent e8a9b56 commit 25653d2

File tree

2 files changed

+14
-25
lines changed

2 files changed

+14
-25
lines changed

Tests/test_file_palm.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ def roundtrip(tmp_path: Path, mode: str) -> None:
4343

4444
im.save(outfile)
4545
converted = open_with_magick(magick, tmp_path, outfile)
46+
if mode == "P":
47+
assert converted.mode == "P"
48+
49+
im = im.convert("RGB")
50+
converted = converted.convert("RGB")
4651
assert_image_equal(converted, im)
4752

4853

@@ -55,7 +60,6 @@ def test_monochrome(tmp_path: Path) -> None:
5560
roundtrip(tmp_path, mode)
5661

5762

58-
@pytest.mark.xfail(reason="Palm P image is wrong")
5963
def test_p_mode(tmp_path: Path) -> None:
6064
# Arrange
6165
mode = "P"

src/PIL/PalmImagePlugin.py

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,6 @@ def build_prototype_image() -> Image.Image:
116116

117117
def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
118118
if im.mode == "P":
119-
# we assume this is a color Palm image with the standard colormap,
120-
# unless the "info" dict has a "custom-colormap" field
121-
122119
rawmode = "P"
123120
bpp = 8
124121
version = 1
@@ -172,12 +169,11 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
172169
compression_type = _COMPRESSION_TYPES["none"]
173170

174171
flags = 0
175-
if im.mode == "P" and "custom-colormap" in im.info:
176-
assert im.palette is not None
177-
flags = flags & _FLAGS["custom-colormap"]
178-
colormapsize = 4 * 256 + 2
179-
colormapmode = im.palette.mode
180-
colormap = im.getdata().getpalette()
172+
if im.mode == "P":
173+
flags |= _FLAGS["custom-colormap"]
174+
colormap = im.im.getpalette()
175+
colors = len(colormap) // 3
176+
colormapsize = 4 * colors + 2
181177
else:
182178
colormapsize = 0
183179

@@ -196,22 +192,11 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
196192

197193
# now write colormap if necessary
198194

199-
if colormapsize > 0:
200-
fp.write(o16b(256))
201-
for i in range(256):
195+
if colormapsize:
196+
fp.write(o16b(colors))
197+
for i in range(colors):
202198
fp.write(o8(i))
203-
if colormapmode == "RGB":
204-
fp.write(
205-
o8(colormap[3 * i])
206-
+ o8(colormap[3 * i + 1])
207-
+ o8(colormap[3 * i + 2])
208-
)
209-
elif colormapmode == "RGBA":
210-
fp.write(
211-
o8(colormap[4 * i])
212-
+ o8(colormap[4 * i + 1])
213-
+ o8(colormap[4 * i + 2])
214-
)
199+
fp.write(colormap[3 * i : 3 * i + 3])
215200

216201
# now convert data to raw form
217202
ImageFile._save(

0 commit comments

Comments
 (0)