JpegImagePlugin.py 29 KB

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