Skip to content

Commit

Permalink
Added reading of JPEG2000 palettes
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Mar 11, 2024
1 parent 00d28bd commit 6df2900
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/PIL/Jpeg2KImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import os
import struct

from . import Image, ImageFile, _binary
from . import Image, ImageFile, ImagePalette, _binary


class BoxReader:
Expand Down Expand Up @@ -162,6 +162,7 @@ def _parse_jp2_header(fp):
bpc = None
nc = None
dpi = None # 2-tuple of DPI info, or None
palette = None

while header.has_next_box():
tbox = header.next_box_type()
Expand All @@ -179,6 +180,14 @@ def _parse_jp2_header(fp):
mode = "RGB"
elif nc == 4:
mode = "RGBA"
elif tbox == b"pclr" and mode[0] == "L":
ne, npc = header.read_fields(">HB")
bitdepths = header.read_fields(">" + ("B" * npc))
if max(bitdepths) <= 8:
palette = ImagePalette.ImagePalette()
for i in range(ne):
palette.getcolor(header.read_fields(">" + ("B" * npc)))
mode = "PA" if nc == 2 else "P"

Check warning on line 190 in src/PIL/Jpeg2KImagePlugin.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/Jpeg2KImagePlugin.py#L184-L190

Added lines #L184 - L190 were not covered by tests
elif tbox == b"res ":
res = header.read_boxes()
while res.has_next_box():
Expand All @@ -195,7 +204,7 @@ def _parse_jp2_header(fp):
msg = "Malformed JP2 header"
raise SyntaxError(msg)

return size, mode, mimetype, dpi
return size, mode, mimetype, dpi, palette


##
Expand All @@ -217,7 +226,7 @@ def _open(self):
if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":
self.codec = "jp2"
header = _parse_jp2_header(self.fp)
self._size, self._mode, self.custom_mimetype, dpi = header
self._size, self._mode, self.custom_mimetype, dpi, self.palette = header
if dpi is not None:
self.info["dpi"] = dpi
if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
Expand Down
2 changes: 2 additions & 0 deletions src/libImaging/Jpeg2KDecode.c
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,8 @@ j2ku_sycca_rgba(

static const struct j2k_decode_unpacker j2k_unpackers[] = {
{"L", OPJ_CLRSPC_GRAY, 1, 0, j2ku_gray_l},
{"P", OPJ_CLRSPC_SRGB, 1, 0, j2ku_gray_l},
{"PA", OPJ_CLRSPC_SRGB, 2, 0, j2ku_graya_la},
{"I;16", OPJ_CLRSPC_GRAY, 1, 0, j2ku_gray_i},
{"I;16B", OPJ_CLRSPC_GRAY, 1, 0, j2ku_gray_i},
{"LA", OPJ_CLRSPC_GRAY, 2, 0, j2ku_graya_la},
Expand Down

0 comments on commit 6df2900

Please sign in to comment.