JpegImagePlugin.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # JPEG (JFIF) file handling
  6. #
  7. # See "Digital Compression and Coding of Continuous-Tone Still Images,
  8. # Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
  9. #
  10. # History:
  11. # 1995-09-09 fl Created
  12. # 1995-09-13 fl Added full parser
  13. # 1996-03-25 fl Added hack to use the IJG command line utilities
  14. # 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
  15. # 1996-05-28 fl Added draft support, JFIF version (0.1)
  16. # 1996-12-30 fl Added encoder options, added progression property (0.2)
  17. # 1997-08-27 fl Save mode 1 images as BW (0.3)
  18. # 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
  19. # 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
  20. # 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
  21. # 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
  22. # 2003-04-25 fl Added experimental EXIF decoder (0.5)
  23. # 2003-06-06 fl Added experimental EXIF GPSinfo decoder
  24. # 2003-09-13 fl Extract COM markers
  25. # 2009-09-06 fl Added icc_profile support (from Florian Hoech)
  26. # 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
  27. # 2009-03-08 fl Added subsampling support (from Justin Huff).
  28. #
  29. # Copyright (c) 1997-2003 by Secret Labs AB.
  30. # Copyright (c) 1995-1996 by Fredrik Lundh.
  31. #
  32. # See the README file for information on usage and redistribution.
  33. #
  34. from __future__ import annotations
  35. __lazy_modules__ = {
  36. "PIL.JpegPresets",
  37. "PIL._binary",
  38. "array",
  39. "io",
  40. "math",
  41. "struct",
  42. "subprocess",
  43. "warnings",
  44. }
  45. import array
  46. import io
  47. import math
  48. import os
  49. import struct
  50. import subprocess
  51. import sys
  52. import warnings
  53. from . import Image, ImageFile
  54. from ._binary import i16be as i16
  55. from ._binary import i32be as i32
  56. from ._binary import o8
  57. from ._binary import o16be as o16
  58. from ._deprecate import deprecate
  59. from .JpegPresets import presets
  60. TYPE_CHECKING = False
  61. if TYPE_CHECKING:
  62. from typing import IO, Any
  63. from .MpoImagePlugin import MpoImageFile
  64. #
  65. # Parser
  66. def Skip(self: JpegImageFile, marker: int) -> None:
  67. assert self.fp is not None
  68. n = i16(self.fp.read(2)) - 2
  69. ImageFile._safe_read(self.fp, n)
  70. def APP(self: JpegImageFile, marker: int) -> None:
  71. #
  72. # Application marker. Store these in the APP dictionary.
  73. # Also look for well-known application markers.
  74. assert self.fp is not None
  75. n = i16(self.fp.read(2)) - 2
  76. s = ImageFile._safe_read(self.fp, n)
  77. app = f"APP{marker & 15}"
  78. self.app[app] = s # compatibility
  79. self.applist.append((app, s))
  80. if marker == 0xFFE0 and s.startswith(b"JFIF"):
  81. # extract JFIF information
  82. self.info["jfif"] = version = i16(s, 5) # version
  83. self.info["jfif_version"] = divmod(version, 256)
  84. # extract JFIF properties
  85. try:
  86. jfif_unit = s[7]
  87. jfif_density = i16(s, 8), i16(s, 10)
  88. except Exception:
  89. pass
  90. else:
  91. if jfif_unit == 1:
  92. self.info["dpi"] = jfif_density
  93. elif jfif_unit == 2: # cm
  94. # 1 dpcm = 2.54 dpi
  95. self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)
  96. self.info["jfif_unit"] = jfif_unit
  97. self.info["jfif_density"] = jfif_density
  98. elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):
  99. # extract EXIF information
  100. if "exif" in self.info:
  101. self.info["exif"] += s[6:]
  102. else:
  103. self.info["exif"] = s
  104. self._exif_offset = self.fp.tell() - n + 6
  105. elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
  106. self.info["xmp"] = s.split(b"\x00", 1)[1]
  107. elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):
  108. # extract FlashPix information (incomplete)
  109. self.info["flashpix"] = s # FIXME: value will change
  110. elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):
  111. # Since an ICC profile can be larger than the maximum size of
  112. # a JPEG marker (64K), we need provisions to split it into
  113. # multiple markers. The format defined by the ICC specifies
  114. # one or more APP2 markers containing the following data:
  115. # Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
  116. # Marker sequence number 1, 2, etc (1 byte)
  117. # Number of markers Total of APP2's used (1 byte)
  118. # Profile data (remainder of APP2 data)
  119. # Decoders should use the marker sequence numbers to
  120. # reassemble the profile, rather than assuming that the APP2
  121. # markers appear in the correct sequence.
  122. self.icclist.append(s)
  123. elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):
  124. # parse the image resource block
  125. offset = 14
  126. photoshop = self.info.setdefault("photoshop", {})
  127. try:
  128. while s[offset : offset + 4] == b"8BIM":
  129. offset += 4
  130. # resource code
  131. code = i16(s, offset)
  132. offset += 2
  133. # resource name (usually empty)
  134. name_len = s[offset]
  135. # name = s[offset+1:offset+1+name_len]
  136. offset += 1 + name_len
  137. offset += offset & 1 # align
  138. # resource data block
  139. size = i32(s, offset)
  140. offset += 4
  141. data = s[offset : offset + size]
  142. if code == 0x03ED: # ResolutionInfo
  143. photoshop[code] = {
  144. "XResolution": i32(data, 0) / 65536,
  145. "DisplayedUnitsX": i16(data, 4),
  146. "YResolution": i32(data, 8) / 65536,
  147. "DisplayedUnitsY": i16(data, 12),
  148. }
  149. else:
  150. photoshop[code] = data
  151. offset += size
  152. offset += offset & 1 # align
  153. except struct.error:
  154. pass # insufficient data
  155. elif marker == 0xFFEE and s.startswith(b"Adobe"):
  156. self.info["adobe"] = i16(s, 5)
  157. # extract Adobe custom properties
  158. try:
  159. adobe_transform = s[11]
  160. except IndexError:
  161. pass
  162. else:
  163. self.info["adobe_transform"] = adobe_transform
  164. elif marker == 0xFFE2 and s.startswith(b"MPF\0"):
  165. # extract MPO information
  166. self.info["mp"] = s[4:]
  167. # offset is current location minus buffer size
  168. # plus constant header size
  169. self.info["mpoffset"] = self.fp.tell() - n + 4
  170. def COM(self: JpegImageFile, marker: int) -> None:
  171. #
  172. # Comment marker. Store these in the APP dictionary.
  173. assert self.fp is not None
  174. n = i16(self.fp.read(2)) - 2
  175. s = ImageFile._safe_read(self.fp, n)
  176. self.info["comment"] = s
  177. self.app["COM"] = s # compatibility
  178. self.applist.append(("COM", s))
  179. def SOF(self: JpegImageFile, marker: int) -> None:
  180. #
  181. # Start of frame marker. Defines the size and mode of the
  182. # image. JPEG is colour blind, so we use some simple
  183. # heuristics to map the number of layers to an appropriate
  184. # mode. Note that this could be made a bit brighter, by
  185. # looking for JFIF and Adobe APP markers.
  186. assert self.fp is not None
  187. n = i16(self.fp.read(2)) - 2
  188. s = ImageFile._safe_read(self.fp, n)
  189. self._size = i16(s, 3), i16(s, 1)
  190. self.bits = s[0]
  191. if self.bits != 8:
  192. msg = f"cannot handle {self.bits}-bit layers"
  193. raise SyntaxError(msg)
  194. self.layers = s[5]
  195. if self.layers == 1:
  196. self._mode = "L"
  197. elif self.layers == 3:
  198. self._mode = "RGB"
  199. elif self.layers == 4:
  200. self._mode = "CMYK"
  201. else:
  202. msg = f"cannot handle {self.layers}-layer images"
  203. raise SyntaxError(msg)
  204. if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
  205. self.info["progressive"] = self.info["progression"] = 1
  206. if self.icclist:
  207. # fixup icc profile
  208. self.icclist.sort() # sort by sequence number
  209. if self.icclist[0][13] == len(self.icclist):
  210. profile = [p[14:] for p in self.icclist]
  211. icc_profile = b"".join(profile)
  212. else:
  213. icc_profile = None # wrong number of fragments
  214. self.info["icc_profile"] = icc_profile
  215. self.icclist = []
  216. for i in range(6, len(s), 3):
  217. t = s[i : i + 3]
  218. # 4-tuples: id, vsamp, hsamp, qtable
  219. self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))
  220. def DQT(self: JpegImageFile, marker: int) -> None:
  221. #
  222. # Define quantization table. Note that there might be more
  223. # than one table in each marker.
  224. # FIXME: The quantization tables can be used to estimate the
  225. # compression quality.
  226. assert self.fp is not None
  227. n = i16(self.fp.read(2)) - 2
  228. s = ImageFile._safe_read(self.fp, n)
  229. while len(s):
  230. v = s[0]
  231. precision = 1 if (v // 16 == 0) else 2 # in bytes
  232. qt_length = 1 + precision * 64
  233. if len(s) < qt_length:
  234. msg = "bad quantization table marker"
  235. raise SyntaxError(msg)
  236. data = array.array("B" if precision == 1 else "H", s[1:qt_length])
  237. if sys.byteorder == "little" and precision > 1:
  238. data.byteswap() # the values are always big-endian
  239. self.quantization[v & 15] = [data[i] for i in zigzag_index]
  240. s = s[qt_length:]
  241. #
  242. # JPEG marker table
  243. MARKER = {
  244. 0xFFC0: ("SOF0", "Baseline DCT", SOF),
  245. 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
  246. 0xFFC2: ("SOF2", "Progressive DCT", SOF),
  247. 0xFFC3: ("SOF3", "Spatial lossless", SOF),
  248. 0xFFC4: ("DHT", "Define Huffman table", Skip),
  249. 0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
  250. 0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
  251. 0xFFC7: ("SOF7", "Differential spatial", SOF),
  252. 0xFFC8: ("JPG", "Extension", None),
  253. 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
  254. 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
  255. 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
  256. 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
  257. 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
  258. 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
  259. 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
  260. 0xFFD0: ("RST0", "Restart 0", None),
  261. 0xFFD1: ("RST1", "Restart 1", None),
  262. 0xFFD2: ("RST2", "Restart 2", None),
  263. 0xFFD3: ("RST3", "Restart 3", None),
  264. 0xFFD4: ("RST4", "Restart 4", None),
  265. 0xFFD5: ("RST5", "Restart 5", None),
  266. 0xFFD6: ("RST6", "Restart 6", None),
  267. 0xFFD7: ("RST7", "Restart 7", None),
  268. 0xFFD8: ("SOI", "Start of image", None),
  269. 0xFFD9: ("EOI", "End of image", None),
  270. 0xFFDA: ("SOS", "Start of scan", Skip),
  271. 0xFFDB: ("DQT", "Define quantization table", DQT),
  272. 0xFFDC: ("DNL", "Define number of lines", Skip),
  273. 0xFFDD: ("DRI", "Define restart interval", Skip),
  274. 0xFFDE: ("DHP", "Define hierarchical progression", SOF),
  275. 0xFFDF: ("EXP", "Expand reference component", Skip),
  276. 0xFFE0: ("APP0", "Application segment 0", APP),
  277. 0xFFE1: ("APP1", "Application segment 1", APP),
  278. 0xFFE2: ("APP2", "Application segment 2", APP),
  279. 0xFFE3: ("APP3", "Application segment 3", APP),
  280. 0xFFE4: ("APP4", "Application segment 4", APP),
  281. 0xFFE5: ("APP5", "Application segment 5", APP),
  282. 0xFFE6: ("APP6", "Application segment 6", APP),
  283. 0xFFE7: ("APP7", "Application segment 7", APP),
  284. 0xFFE8: ("APP8", "Application segment 8", APP),
  285. 0xFFE9: ("APP9", "Application segment 9", APP),
  286. 0xFFEA: ("APP10", "Application segment 10", APP),
  287. 0xFFEB: ("APP11", "Application segment 11", APP),
  288. 0xFFEC: ("APP12", "Application segment 12", APP),
  289. 0xFFED: ("APP13", "Application segment 13", APP),
  290. 0xFFEE: ("APP14", "Application segment 14", APP),
  291. 0xFFEF: ("APP15", "Application segment 15", APP),
  292. 0xFFF0: ("JPG0", "Extension 0", None),
  293. 0xFFF1: ("JPG1", "Extension 1", None),
  294. 0xFFF2: ("JPG2", "Extension 2", None),
  295. 0xFFF3: ("JPG3", "Extension 3", None),
  296. 0xFFF4: ("JPG4", "Extension 4", None),
  297. 0xFFF5: ("JPG5", "Extension 5", None),
  298. 0xFFF6: ("JPG6", "Extension 6", None),
  299. 0xFFF7: ("JPG7", "Extension 7", None),
  300. 0xFFF8: ("JPG8", "Extension 8", None),
  301. 0xFFF9: ("JPG9", "Extension 9", None),
  302. 0xFFFA: ("JPG10", "Extension 10", None),
  303. 0xFFFB: ("JPG11", "Extension 11", None),
  304. 0xFFFC: ("JPG12", "Extension 12", None),
  305. 0xFFFD: ("JPG13", "Extension 13", None),
  306. 0xFFFE: ("COM", "Comment", COM),
  307. }
  308. def _accept(prefix: bytes) -> bool:
  309. # Magic number was taken from https://en.wikipedia.org/wiki/JPEG
  310. return prefix.startswith(b"\xff\xd8\xff")
  311. ##
  312. # Image plugin for JPEG and JFIF images.
  313. class JpegImageFile(ImageFile.ImageFile):
  314. format = "JPEG"
  315. format_description = "JPEG (ISO 10918)"
  316. def _open(self) -> None:
  317. assert self.fp is not None
  318. s = self.fp.read(3)
  319. if not _accept(s):
  320. msg = "not a JPEG file"
  321. raise SyntaxError(msg)
  322. s = b"\xff"
  323. # Create attributes
  324. self.bits = self.layers = 0
  325. self._exif_offset = 0
  326. # JPEG specifics (internal)
  327. self.layer: list[tuple[int, int, int, int]] = []
  328. self._huffman_dc: dict[Any, Any] = {}
  329. self._huffman_ac: dict[Any, Any] = {}
  330. self.quantization: dict[int, list[int]] = {}
  331. self.app: dict[str, bytes] = {} # compatibility
  332. self.applist: list[tuple[str, bytes]] = []
  333. self.icclist: list[bytes] = []
  334. while s:
  335. i = s[0]
  336. if i == 0xFF:
  337. s += self.fp.read(1)
  338. if len(s) < 2:
  339. break
  340. i = i16(s)
  341. else:
  342. # Skip non-0xFF junk
  343. s = self.fp.read(1)
  344. continue
  345. if i in MARKER:
  346. name, description, handler = MARKER[i]
  347. if handler is not None:
  348. handler(self, i)
  349. if i == 0xFFDA: # start of scan
  350. rawmode = self.mode
  351. if self.mode == "CMYK":
  352. rawmode = "CMYK;I" # assume adobe conventions
  353. self.tile = [
  354. ImageFile._Tile("jpeg", (0, 0, *self.size), 0, (rawmode, ""))
  355. ]
  356. # self.__offset = self.fp.tell()
  357. break
  358. s = self.fp.read(1)
  359. elif i in {0, 0xFFFF}:
  360. # padded marker or junk; move on
  361. s = b"\xff"
  362. elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)
  363. s = self.fp.read(1)
  364. else:
  365. msg = "no marker found"
  366. raise SyntaxError(msg)
  367. self._read_dpi_from_exif()
  368. def __getstate__(self) -> list[Any]:
  369. return super().__getstate__() + [self.layers, self.layer]
  370. def __setstate__(self, state: list[Any]) -> None:
  371. self.layers, self.layer = state[6:]
  372. super().__setstate__(state)
  373. def load_read(self, read_bytes: int) -> bytes:
  374. """
  375. internal: read more image data
  376. For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker
  377. so libjpeg can finish decoding
  378. """
  379. assert self.fp is not None
  380. s = self.fp.read(read_bytes)
  381. if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):
  382. # Premature EOF.
  383. # Pretend file is finished adding EOI marker
  384. self._ended = True
  385. return b"\xff\xd9"
  386. return s
  387. def draft(
  388. self, mode: str | None, size: tuple[int, int] | None
  389. ) -> tuple[str, tuple[int, int, float, float]] | None:
  390. if len(self.tile) != 1:
  391. return None
  392. # Protect from second call
  393. if self.decoderconfig:
  394. return None
  395. d, e, o, a = self.tile[0]
  396. scale = 1
  397. original_size = self.size
  398. assert isinstance(a, tuple)
  399. if a[0] == "RGB" and mode in ["L", "YCbCr"]:
  400. self._mode = mode
  401. a = mode, ""
  402. if size:
  403. scale = min(self.size[0] // size[0], self.size[1] // size[1])
  404. for s in [8, 4, 2, 1]:
  405. if scale >= s:
  406. break
  407. assert e is not None
  408. e = (
  409. e[0],
  410. e[1],
  411. (e[2] - e[0] + s - 1) // s + e[0],
  412. (e[3] - e[1] + s - 1) // s + e[1],
  413. )
  414. self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)
  415. scale = s
  416. self.tile = [ImageFile._Tile(d, e, o, a)]
  417. self.decoderconfig = (scale, 0)
  418. box = (0, 0, original_size[0] / scale, original_size[1] / scale)
  419. return self.mode, box
  420. def load_djpeg(self) -> None:
  421. # ALTERNATIVE: handle JPEGs via the IJG command line utilities
  422. import tempfile
  423. deprecate(
  424. "load_djpeg",
  425. 14,
  426. action="Use the built-in JPEG decoder instead, or call djpeg yourself.",
  427. )
  428. f, path = tempfile.mkstemp()
  429. os.close(f)
  430. if os.path.exists(self.filename):
  431. subprocess.check_call(["djpeg", "-outfile", path, self.filename])
  432. else:
  433. try:
  434. os.unlink(path)
  435. except OSError:
  436. pass
  437. msg = "Invalid Filename"
  438. raise ValueError(msg)
  439. try:
  440. with Image.open(path) as _im:
  441. _im.load()
  442. self.im = _im.im
  443. finally:
  444. try:
  445. os.unlink(path)
  446. except OSError:
  447. pass
  448. self._mode = self.im.mode
  449. self._size = self.im.size
  450. self.tile = []
  451. def _getexif(self) -> dict[int, Any] | None:
  452. return _getexif(self)
  453. def _read_dpi_from_exif(self) -> None:
  454. # If DPI isn't in JPEG header, fetch from EXIF
  455. if "dpi" in self.info or "exif" not in self.info:
  456. return
  457. try:
  458. exif = self.getexif()
  459. resolution_unit = exif[0x0128]
  460. x_resolution = exif[0x011A]
  461. try:
  462. dpi = float(x_resolution[0]) / x_resolution[1]
  463. except TypeError:
  464. dpi = x_resolution
  465. if math.isnan(dpi):
  466. msg = "DPI is not a number"
  467. raise ValueError(msg)
  468. if resolution_unit == 3: # cm
  469. # 1 dpcm = 2.54 dpi
  470. dpi *= 2.54
  471. self.info["dpi"] = dpi, dpi
  472. except (
  473. struct.error, # truncated EXIF
  474. KeyError, # dpi not included
  475. SyntaxError, # invalid/unreadable EXIF
  476. TypeError, # dpi is an invalid float
  477. ValueError, # dpi is an invalid float
  478. ZeroDivisionError, # invalid dpi rational value
  479. ):
  480. self.info["dpi"] = 72, 72
  481. def _getmp(self) -> dict[int, Any] | None:
  482. return _getmp(self)
  483. def _getexif(self: JpegImageFile) -> dict[int, Any] | None:
  484. if "exif" not in self.info:
  485. return None
  486. return self.getexif()._get_merged_dict()
  487. def _getmp(self: JpegImageFile) -> dict[int, Any] | None:
  488. # Extract MP information. This method was inspired by the "highly
  489. # experimental" _getexif version that's been in use for years now,
  490. # itself based on the ImageFileDirectory class in the TIFF plugin.
  491. # The MP record essentially consists of a TIFF file embedded in a JPEG
  492. # application marker.
  493. try:
  494. data = self.info["mp"]
  495. except KeyError:
  496. return None
  497. file_contents = io.BytesIO(data)
  498. head = file_contents.read(8)
  499. endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"
  500. # process dictionary
  501. from . import TiffImagePlugin
  502. try:
  503. info = TiffImagePlugin.ImageFileDirectory_v2(head)
  504. file_contents.seek(info.next)
  505. info.load(file_contents)
  506. mp = dict(info)
  507. except Exception as e:
  508. msg = "malformed MP Index (unreadable directory)"
  509. raise SyntaxError(msg) from e
  510. # it's an error not to have a number of images
  511. try:
  512. quant = mp[0xB001]
  513. except KeyError as e:
  514. msg = "malformed MP Index (no number of images)"
  515. raise SyntaxError(msg) from e
  516. # get MP entries
  517. mpentries = []
  518. try:
  519. rawmpentries = mp[0xB002]
  520. for entrynum in range(quant):
  521. unpackedentry = struct.unpack_from(
  522. f"{endianness}LLLHH", rawmpentries, entrynum * 16
  523. )
  524. labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")
  525. mpentry = dict(zip(labels, unpackedentry))
  526. mpentryattr = {
  527. "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),
  528. "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),
  529. "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),
  530. "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,
  531. "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,
  532. "MPType": mpentry["Attribute"] & 0x00FFFFFF,
  533. }
  534. if mpentryattr["ImageDataFormat"] == 0:
  535. mpentryattr["ImageDataFormat"] = "JPEG"
  536. else:
  537. msg = "unsupported picture format in MPO"
  538. raise SyntaxError(msg)
  539. mptypemap = {
  540. 0x000000: "Undefined",
  541. 0x010001: "Large Thumbnail (VGA Equivalent)",
  542. 0x010002: "Large Thumbnail (Full HD Equivalent)",
  543. 0x020001: "Multi-Frame Image (Panorama)",
  544. 0x020002: "Multi-Frame Image: (Disparity)",
  545. 0x020003: "Multi-Frame Image: (Multi-Angle)",
  546. 0x030000: "Baseline MP Primary Image",
  547. }
  548. mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")
  549. mpentry["Attribute"] = mpentryattr
  550. mpentries.append(mpentry)
  551. mp[0xB002] = mpentries
  552. except (KeyError, struct.error) as e:
  553. msg = "malformed MP Index (bad MP Entry)"
  554. raise SyntaxError(msg) from e
  555. # Next we should try and parse the individual image unique ID list;
  556. # we don't because I've never seen this actually used in a real MPO
  557. # file and so can't test it.
  558. return mp
  559. # --------------------------------------------------------------------
  560. # stuff to save JPEG files
  561. RAWMODE = {
  562. "1": "L",
  563. "L": "L",
  564. "RGB": "RGB",
  565. "RGBX": "RGB",
  566. "CMYK": "CMYK;I", # assume adobe conventions
  567. "YCbCr": "YCbCr",
  568. }
  569. zigzag_index = (
  570. 0, 1, 5, 6, 14, 15, 27, 28,
  571. 2, 4, 7, 13, 16, 26, 29, 42,
  572. 3, 8, 12, 17, 25, 30, 41, 43,
  573. 9, 11, 18, 24, 31, 40, 44, 53,
  574. 10, 19, 23, 32, 39, 45, 52, 54,
  575. 20, 22, 33, 38, 46, 51, 55, 60,
  576. 21, 34, 37, 47, 50, 56, 59, 61,
  577. 35, 36, 48, 49, 57, 58, 62, 63,
  578. ) # fmt: skip
  579. samplings = {
  580. (1, 1, 1, 1, 1, 1): 0,
  581. (2, 1, 1, 1, 1, 1): 1,
  582. (2, 2, 1, 1, 1, 1): 2,
  583. }
  584. def get_sampling(im: Image.Image) -> int:
  585. # There's no subsampling when images have only 1 layer
  586. # (grayscale images) or when they are CMYK (4 layers),
  587. # so set subsampling to the default value.
  588. #
  589. # NOTE: currently Pillow can't encode JPEG to YCCK format.
  590. # If YCCK support is added in the future, subsampling code will have
  591. # to be updated (here and in JpegEncode.c) to deal with 4 layers.
  592. if not isinstance(im, JpegImageFile) or im.layers in (1, 4):
  593. return -1
  594. sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
  595. return samplings.get(sampling, -1)
  596. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  597. try:
  598. rawmode = RAWMODE[im.mode]
  599. except KeyError as e:
  600. msg = f"cannot write mode {im.mode} as JPEG"
  601. raise OSError(msg) from e
  602. info = im.encoderinfo
  603. dpi = [round(x) for x in info.get("dpi", (0, 0))]
  604. quality = info.get("quality", -1)
  605. subsampling = info.get("subsampling", -1)
  606. qtables = info.get("qtables")
  607. if quality == "keep":
  608. quality = -1
  609. subsampling = "keep"
  610. qtables = "keep"
  611. elif quality in presets:
  612. preset = presets[quality]
  613. quality = -1
  614. subsampling = preset.get("subsampling", -1)
  615. qtables = preset.get("quantization")
  616. elif not isinstance(quality, int):
  617. msg = "Invalid quality setting"
  618. raise ValueError(msg)
  619. else:
  620. if subsampling in presets:
  621. subsampling = presets[subsampling].get("subsampling", -1)
  622. if isinstance(qtables, str) and qtables in presets:
  623. qtables = presets[qtables].get("quantization")
  624. if subsampling == "4:4:4":
  625. subsampling = 0
  626. elif subsampling == "4:2:2":
  627. subsampling = 1
  628. elif subsampling == "4:2:0":
  629. subsampling = 2
  630. elif subsampling == "4:1:1":
  631. # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.
  632. # Set 4:2:0 if someone is still using that value.
  633. subsampling = 2
  634. elif subsampling == "keep":
  635. if im.format != "JPEG":
  636. msg = "Cannot use 'keep' when original image is not a JPEG"
  637. raise ValueError(msg)
  638. subsampling = get_sampling(im)
  639. def validate_qtables(
  640. qtables: (
  641. str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None
  642. ),
  643. ) -> list[list[int]] | None:
  644. if qtables is None:
  645. return qtables
  646. if isinstance(qtables, str):
  647. try:
  648. lines = [
  649. int(num)
  650. for line in qtables.splitlines()
  651. for num in line.split("#", 1)[0].split()
  652. ]
  653. except ValueError as e:
  654. msg = "Invalid quantization table"
  655. raise ValueError(msg) from e
  656. else:
  657. qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]
  658. if isinstance(qtables, (tuple, list, dict)):
  659. if isinstance(qtables, dict):
  660. qtables = [
  661. qtables[key] for key in range(len(qtables)) if key in qtables
  662. ]
  663. else:
  664. # Copy the sequence, so that it cannot be changed while it is read
  665. qtables = list(qtables)
  666. if not (0 < len(qtables) < 5):
  667. msg = "None or too many quantization tables"
  668. raise ValueError(msg)
  669. try:
  670. for idx, table in enumerate(qtables):
  671. if len(table) != 64:
  672. msg = "Invalid quantization table"
  673. raise TypeError(msg)
  674. qtables[idx] = list(array.array("H", table))
  675. except TypeError as e:
  676. msg = "Invalid quantization table"
  677. raise ValueError(msg) from e
  678. return qtables
  679. if qtables == "keep":
  680. if im.format != "JPEG":
  681. msg = "Cannot use 'keep' when original image is not a JPEG"
  682. raise ValueError(msg)
  683. qtables = getattr(im, "quantization", None)
  684. qtables = validate_qtables(qtables)
  685. extra = info.get("extra", b"")
  686. MAX_BYTES_IN_MARKER = 65533
  687. if xmp := info.get("xmp"):
  688. overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00"
  689. max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
  690. if len(xmp) > max_data_bytes_in_marker:
  691. msg = "XMP data is too long"
  692. raise ValueError(msg)
  693. size = o16(2 + overhead_len + len(xmp))
  694. extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp
  695. if icc_profile := info.get("icc_profile"):
  696. overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers))
  697. max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len
  698. markers = []
  699. while icc_profile:
  700. markers.append(icc_profile[:max_data_bytes_in_marker])
  701. icc_profile = icc_profile[max_data_bytes_in_marker:]
  702. i = 1
  703. for marker in markers:
  704. size = o16(2 + overhead_len + len(marker))
  705. extra += (
  706. b"\xff\xe2"
  707. + size
  708. + b"ICC_PROFILE\0"
  709. + o8(i)
  710. + o8(len(markers))
  711. + marker
  712. )
  713. i += 1
  714. comment = info.get("comment", im.info.get("comment"))
  715. if comment and len(comment) > MAX_BYTES_IN_MARKER:
  716. msg = "Comment is too long"
  717. raise ValueError(msg)
  718. # "progressive" is the official name, but older documentation
  719. # says "progression"
  720. # FIXME: issue a warning if the wrong form is used (post-1.1.7)
  721. progressive = info.get("progressive", False) or info.get("progression", False)
  722. optimize = info.get("optimize", False)
  723. exif = info.get("exif", b"")
  724. if isinstance(exif, Image.Exif):
  725. exif = exif.tobytes()
  726. if len(exif) > MAX_BYTES_IN_MARKER:
  727. msg = "EXIF data is too long"
  728. raise ValueError(msg)
  729. # get keyword arguments
  730. im.encoderconfig = (
  731. quality,
  732. progressive,
  733. info.get("smooth", 0),
  734. optimize,
  735. info.get("keep_rgb", False),
  736. info.get("streamtype", 0),
  737. dpi,
  738. subsampling,
  739. info.get("restart_marker_blocks", 0),
  740. info.get("restart_marker_rows", 0),
  741. qtables,
  742. comment,
  743. extra,
  744. exif,
  745. )
  746. # if we optimize, libjpeg needs a buffer big enough to hold the whole image
  747. # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is
  748. # channels*size, this is a value that's been used in a Django patch.
  749. # https://github.com/matthewwithanm/django-imagekit/issues/50
  750. if optimize or progressive:
  751. # CMYK can be bigger
  752. if im.mode == "CMYK":
  753. bufsize = 4 * im.size[0] * im.size[1]
  754. # keep sets quality to -1, but the actual value may be high.
  755. elif quality >= 95 or quality == -1:
  756. bufsize = 2 * im.size[0] * im.size[1]
  757. else:
  758. bufsize = im.size[0] * im.size[1]
  759. if exif:
  760. bufsize += len(exif) + 5
  761. if extra:
  762. bufsize += len(extra)
  763. if comment:
  764. bufsize += len(comment) + 5
  765. else:
  766. # The EXIF info needs to be written as one block, + APP1, + one spare byte,
  767. # as libjpeg without suspension requires one byte left after writing a marker.
  768. # Ensure that our buffer is big enough. Same with the icc_profile block
  769. # and the comment (COM marker).
  770. bufsize = max(len(exif) + 5, len(extra), len(comment or b"") + 5)
  771. ImageFile._save(
  772. im, fp, [ImageFile._Tile("jpeg", (0, 0, *im.size), 0, rawmode)], bufsize
  773. )
  774. ##
  775. # Factory for making JPEG and MPO instances
  776. def jpeg_factory(
  777. fp: IO[bytes], filename: str | bytes | None = None
  778. ) -> JpegImageFile | MpoImageFile:
  779. im = JpegImageFile(fp, filename)
  780. try:
  781. mpheader = im._getmp()
  782. if mpheader is not None and mpheader[45057] > 1:
  783. for segment, content in im.applist:
  784. if segment == "APP1" and b' hdrgm:Version="' in content:
  785. # Ultra HDR images are not yet supported
  786. return im
  787. # It's actually an MPO
  788. from .MpoImagePlugin import MpoImageFile
  789. # Don't reload everything, just convert it.
  790. im = MpoImageFile.adopt(im, mpheader)
  791. except (TypeError, IndexError):
  792. # It is really a JPEG
  793. pass
  794. except SyntaxError:
  795. warnings.warn(
  796. "Image appears to be a malformed MPO file, it will be "
  797. "interpreted as a base JPEG file"
  798. )
  799. return im
  800. # ---------------------------------------------------------------------
  801. # Registry stuff
  802. Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
  803. Image.register_save(JpegImageFile.format, _save)
  804. Image.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])
  805. Image.register_mime(JpegImageFile.format, "image/jpeg")