Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Jpeg2KImagePlugin.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # JPEG2000 file handling
  6. #
  7. # History:
  8. # 2014-03-12 ajh Created
  9. # 2021-06-30 rogermb Extract dpi information from the 'resc' header box
  10. #
  11. # Copyright (c) 2014 Coriolis Systems Limited
  12. # Copyright (c) 2014 Alastair Houghton
  13. #
  14. # See the README file for information on usage and redistribution.
  15. #
  16. import io
  17. import os
  18. import struct
  19. from . import Image, ImageFile, _binary
  20. class BoxReader:
  21. """
  22. A small helper class to read fields stored in JPEG2000 header boxes
  23. and to easily step into and read sub-boxes.
  24. """
  25. def __init__(self, fp, length=-1):
  26. self.fp = fp
  27. self.has_length = length >= 0
  28. self.length = length
  29. self.remaining_in_box = -1
  30. def _can_read(self, num_bytes):
  31. if self.has_length and self.fp.tell() + num_bytes > self.length:
  32. # Outside box: ensure we don't read past the known file length
  33. return False
  34. if self.remaining_in_box >= 0:
  35. # Inside box contents: ensure read does not go past box boundaries
  36. return num_bytes <= self.remaining_in_box
  37. else:
  38. return True # No length known, just read
  39. def _read_bytes(self, num_bytes):
  40. if not self._can_read(num_bytes):
  41. msg = "Not enough data in header"
  42. raise SyntaxError(msg)
  43. data = self.fp.read(num_bytes)
  44. if len(data) < num_bytes:
  45. msg = f"Expected to read {num_bytes} bytes but only got {len(data)}."
  46. raise OSError(msg)
  47. if self.remaining_in_box > 0:
  48. self.remaining_in_box -= num_bytes
  49. return data
  50. def read_fields(self, field_format):
  51. size = struct.calcsize(field_format)
  52. data = self._read_bytes(size)
  53. return struct.unpack(field_format, data)
  54. def read_boxes(self):
  55. size = self.remaining_in_box
  56. data = self._read_bytes(size)
  57. return BoxReader(io.BytesIO(data), size)
  58. def has_next_box(self):
  59. if self.has_length:
  60. return self.fp.tell() + self.remaining_in_box < self.length
  61. else:
  62. return True
  63. def next_box_type(self):
  64. # Skip the rest of the box if it has not been read
  65. if self.remaining_in_box > 0:
  66. self.fp.seek(self.remaining_in_box, os.SEEK_CUR)
  67. self.remaining_in_box = -1
  68. # Read the length and type of the next box
  69. lbox, tbox = self.read_fields(">I4s")
  70. if lbox == 1:
  71. lbox = self.read_fields(">Q")[0]
  72. hlen = 16
  73. else:
  74. hlen = 8
  75. if lbox < hlen or not self._can_read(lbox - hlen):
  76. msg = "Invalid header length"
  77. raise SyntaxError(msg)
  78. self.remaining_in_box = lbox - hlen
  79. return tbox
  80. def _parse_codestream(fp):
  81. """Parse the JPEG 2000 codestream to extract the size and component
  82. count from the SIZ marker segment, returning a PIL (size, mode) tuple."""
  83. hdr = fp.read(2)
  84. lsiz = _binary.i16be(hdr)
  85. siz = hdr + fp.read(lsiz - 2)
  86. lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(
  87. ">HHIIIIIIIIH", siz
  88. )
  89. ssiz = [None] * csiz
  90. xrsiz = [None] * csiz
  91. yrsiz = [None] * csiz
  92. for i in range(csiz):
  93. ssiz[i], xrsiz[i], yrsiz[i] = struct.unpack_from(">BBB", siz, 36 + 3 * i)
  94. size = (xsiz - xosiz, ysiz - yosiz)
  95. if csiz == 1:
  96. if (yrsiz[0] & 0x7F) > 8:
  97. mode = "I;16"
  98. else:
  99. mode = "L"
  100. elif csiz == 2:
  101. mode = "LA"
  102. elif csiz == 3:
  103. mode = "RGB"
  104. elif csiz == 4:
  105. mode = "RGBA"
  106. else:
  107. mode = None
  108. return size, mode
  109. def _res_to_dpi(num, denom, exp):
  110. """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution,
  111. calculated as (num / denom) * 10^exp and stored in dots per meter,
  112. to floating-point dots per inch."""
  113. if denom != 0:
  114. return (254 * num * (10**exp)) / (10000 * denom)
  115. def _parse_jp2_header(fp):
  116. """Parse the JP2 header box to extract size, component count,
  117. color space information, and optionally DPI information,
  118. returning a (size, mode, mimetype, dpi) tuple."""
  119. # Find the JP2 header box
  120. reader = BoxReader(fp)
  121. header = None
  122. mimetype = None
  123. while reader.has_next_box():
  124. tbox = reader.next_box_type()
  125. if tbox == b"jp2h":
  126. header = reader.read_boxes()
  127. break
  128. elif tbox == b"ftyp":
  129. if reader.read_fields(">4s")[0] == b"jpx ":
  130. mimetype = "image/jpx"
  131. size = None
  132. mode = None
  133. bpc = None
  134. nc = None
  135. dpi = None # 2-tuple of DPI info, or None
  136. while header.has_next_box():
  137. tbox = header.next_box_type()
  138. if tbox == b"ihdr":
  139. height, width, nc, bpc = header.read_fields(">IIHB")
  140. size = (width, height)
  141. if nc == 1 and (bpc & 0x7F) > 8:
  142. mode = "I;16"
  143. elif nc == 1:
  144. mode = "L"
  145. elif nc == 2:
  146. mode = "LA"
  147. elif nc == 3:
  148. mode = "RGB"
  149. elif nc == 4:
  150. mode = "RGBA"
  151. elif tbox == b"res ":
  152. res = header.read_boxes()
  153. while res.has_next_box():
  154. tres = res.next_box_type()
  155. if tres == b"resc":
  156. vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")
  157. hres = _res_to_dpi(hrcn, hrcd, hrce)
  158. vres = _res_to_dpi(vrcn, vrcd, vrce)
  159. if hres is not None and vres is not None:
  160. dpi = (hres, vres)
  161. break
  162. if size is None or mode is None:
  163. msg = "Malformed JP2 header"
  164. raise SyntaxError(msg)
  165. return size, mode, mimetype, dpi
  166. ##
  167. # Image plugin for JPEG2000 images.
  168. class Jpeg2KImageFile(ImageFile.ImageFile):
  169. format = "JPEG2000"
  170. format_description = "JPEG 2000 (ISO 15444)"
  171. def _open(self):
  172. sig = self.fp.read(4)
  173. if sig == b"\xff\x4f\xff\x51":
  174. self.codec = "j2k"
  175. self._size, self.mode = _parse_codestream(self.fp)
  176. else:
  177. sig = sig + self.fp.read(8)
  178. if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":
  179. self.codec = "jp2"
  180. header = _parse_jp2_header(self.fp)
  181. self._size, self.mode, self.custom_mimetype, dpi = header
  182. if dpi is not None:
  183. self.info["dpi"] = dpi
  184. if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):
  185. self._parse_comment()
  186. else:
  187. msg = "not a JPEG 2000 file"
  188. raise SyntaxError(msg)
  189. if self.size is None or self.mode is None:
  190. msg = "unable to determine size/mode"
  191. raise SyntaxError(msg)
  192. self._reduce = 0
  193. self.layers = 0
  194. fd = -1
  195. length = -1
  196. try:
  197. fd = self.fp.fileno()
  198. length = os.fstat(fd).st_size
  199. except Exception:
  200. fd = -1
  201. try:
  202. pos = self.fp.tell()
  203. self.fp.seek(0, io.SEEK_END)
  204. length = self.fp.tell()
  205. self.fp.seek(pos)
  206. except Exception:
  207. length = -1
  208. self.tile = [
  209. (
  210. "jpeg2k",
  211. (0, 0) + self.size,
  212. 0,
  213. (self.codec, self._reduce, self.layers, fd, length),
  214. )
  215. ]
  216. def _parse_comment(self):
  217. hdr = self.fp.read(2)
  218. length = _binary.i16be(hdr)
  219. self.fp.seek(length - 2, os.SEEK_CUR)
  220. while True:
  221. marker = self.fp.read(2)
  222. if not marker:
  223. break
  224. typ = marker[1]
  225. if typ in (0x90, 0xD9):
  226. # Start of tile or end of codestream
  227. break
  228. hdr = self.fp.read(2)
  229. length = _binary.i16be(hdr)
  230. if typ == 0x64:
  231. # Comment
  232. self.info["comment"] = self.fp.read(length - 2)[2:]
  233. break
  234. else:
  235. self.fp.seek(length - 2, os.SEEK_CUR)
  236. @property
  237. def reduce(self):
  238. # https://github.com/python-pillow/Pillow/issues/4343 found that the
  239. # new Image 'reduce' method was shadowed by this plugin's 'reduce'
  240. # property. This attempts to allow for both scenarios
  241. return self._reduce or super().reduce
  242. @reduce.setter
  243. def reduce(self, value):
  244. self._reduce = value
  245. def load(self):
  246. if self.tile and self._reduce:
  247. power = 1 << self._reduce
  248. adjust = power >> 1
  249. self._size = (
  250. int((self.size[0] + adjust) / power),
  251. int((self.size[1] + adjust) / power),
  252. )
  253. # Update the reduce and layers settings
  254. t = self.tile[0]
  255. t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])
  256. self.tile = [(t[0], (0, 0) + self.size, t[2], t3)]
  257. return ImageFile.ImageFile.load(self)
  258. def _accept(prefix):
  259. return (
  260. prefix[:4] == b"\xff\x4f\xff\x51"
  261. or prefix[:12] == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
  262. )
  263. # ------------------------------------------------------------
  264. # Save support
  265. def _save(im, fp, filename):
  266. # Get the keyword arguments
  267. info = im.encoderinfo
  268. if filename.endswith(".j2k") or info.get("no_jp2", False):
  269. kind = "j2k"
  270. else:
  271. kind = "jp2"
  272. offset = info.get("offset", None)
  273. tile_offset = info.get("tile_offset", None)
  274. tile_size = info.get("tile_size", None)
  275. quality_mode = info.get("quality_mode", "rates")
  276. quality_layers = info.get("quality_layers", None)
  277. if quality_layers is not None and not (
  278. isinstance(quality_layers, (list, tuple))
  279. and all(
  280. [
  281. isinstance(quality_layer, (int, float))
  282. for quality_layer in quality_layers
  283. ]
  284. )
  285. ):
  286. msg = "quality_layers must be a sequence of numbers"
  287. raise ValueError(msg)
  288. num_resolutions = info.get("num_resolutions", 0)
  289. cblk_size = info.get("codeblock_size", None)
  290. precinct_size = info.get("precinct_size", None)
  291. irreversible = info.get("irreversible", False)
  292. progression = info.get("progression", "LRCP")
  293. cinema_mode = info.get("cinema_mode", "no")
  294. mct = info.get("mct", 0)
  295. signed = info.get("signed", False)
  296. comment = info.get("comment")
  297. if isinstance(comment, str):
  298. comment = comment.encode()
  299. plt = info.get("plt", False)
  300. fd = -1
  301. if hasattr(fp, "fileno"):
  302. try:
  303. fd = fp.fileno()
  304. except Exception:
  305. fd = -1
  306. im.encoderconfig = (
  307. offset,
  308. tile_offset,
  309. tile_size,
  310. quality_mode,
  311. quality_layers,
  312. num_resolutions,
  313. cblk_size,
  314. precinct_size,
  315. irreversible,
  316. progression,
  317. cinema_mode,
  318. mct,
  319. signed,
  320. fd,
  321. comment,
  322. plt,
  323. )
  324. ImageFile._save(im, fp, [("jpeg2k", (0, 0) + im.size, 0, kind)])
  325. # ------------------------------------------------------------
  326. # Registry stuff
  327. Image.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept)
  328. Image.register_save(Jpeg2KImageFile.format, _save)
  329. Image.register_extensions(
  330. Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"]
  331. )
  332. Image.register_mime(Jpeg2KImageFile.format, "image/jp2")