Skip to content

Commit

Permalink
Corrected P mode save
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Jan 10, 2025
1 parent 8878511 commit 6f42cfe
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 25 deletions.
6 changes: 5 additions & 1 deletion Tests/test_file_palm.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ def roundtrip(tmp_path: Path, mode: str) -> None:

im.save(outfile)
converted = open_with_magick(magick, tmp_path, outfile)
if mode == "P":
assert converted.mode == "P"

im = im.convert("RGB")
converted = converted.convert("RGB")
assert_image_equal(converted, im)


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


@pytest.mark.xfail(reason="Palm P image is wrong")
def test_p_mode(tmp_path: Path) -> None:
# Arrange
mode = "P"
Expand Down
33 changes: 9 additions & 24 deletions src/PIL/PalmImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,6 @@ def build_prototype_image() -> Image.Image:

def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
if im.mode == "P":
# we assume this is a color Palm image with the standard colormap,
# unless the "info" dict has a "custom-colormap" field

rawmode = "P"
bpp = 8
version = 1
Expand Down Expand Up @@ -172,12 +169,11 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
compression_type = _COMPRESSION_TYPES["none"]

flags = 0
if im.mode == "P" and "custom-colormap" in im.info:
assert im.palette is not None
flags = flags & _FLAGS["custom-colormap"]
colormapsize = 4 * 256 + 2
colormapmode = im.palette.mode
colormap = im.getdata().getpalette()
if im.mode == "P":
flags |= _FLAGS["custom-colormap"]
colormap = im.im.getpalette()
colors = len(colormap) // 3
colormapsize = 4 * colors + 2
else:
colormapsize = 0

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

# now write colormap if necessary

if colormapsize > 0:
fp.write(o16b(256))
for i in range(256):
if colormapsize:
fp.write(o16b(colors))
for i in range(colors):
fp.write(o8(i))
if colormapmode == "RGB":
fp.write(
o8(colormap[3 * i])
+ o8(colormap[3 * i + 1])
+ o8(colormap[3 * i + 2])
)
elif colormapmode == "RGBA":
fp.write(
o8(colormap[4 * i])
+ o8(colormap[4 * i + 1])
+ o8(colormap[4 * i + 2])
)
fp.write(colormap[3 * i : 3 * i + 3])

# now convert data to raw form
ImageFile._save(
Expand Down

0 comments on commit 6f42cfe

Please sign in to comment.