MpoImagePlugin.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # MPO file handling
  6. #
  7. # See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the
  8. # Camera & Imaging Products Association)
  9. #
  10. # The multi-picture object combines multiple JPEG images (with a modified EXIF
  11. # data format) into a single file. While it can theoretically be used much like
  12. # a GIF animation, it is commonly used to represent 3D photographs and is (as
  13. # of this writing) the most commonly used format by 3D cameras.
  14. #
  15. # History:
  16. # 2014-03-13 Feneric Created
  17. #
  18. # See the README file for information on usage and redistribution.
  19. #
  20. from __future__ import annotations
  21. __lazy_modules__ = {"PIL._binary", "PIL._util", "struct"}
  22. import os
  23. import struct
  24. from typing import cast
  25. from . import (
  26. Image,
  27. ImageFile,
  28. ImageSequence,
  29. JpegImagePlugin,
  30. TiffImagePlugin,
  31. )
  32. from ._binary import o32le
  33. from ._util import DeferredError
  34. TYPE_CHECKING = False
  35. if TYPE_CHECKING:
  36. from typing import IO, Any
  37. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  38. JpegImagePlugin._save(im, fp, filename)
  39. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  40. append_images = im.encoderinfo.get("append_images", [])
  41. if not append_images and not getattr(im, "is_animated", False):
  42. _save(im, fp, filename)
  43. return
  44. mpf_offset = 28
  45. offsets: list[int] = []
  46. im_sequences = [im, *append_images]
  47. total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences)
  48. for im_sequence in im_sequences:
  49. for im_frame in ImageSequence.Iterator(im_sequence):
  50. if not offsets:
  51. # APP2 marker
  52. ifd_length = 66 + 16 * total
  53. im_frame.encoderinfo["extra"] = (
  54. b"\xff\xe2"
  55. + struct.pack(">H", 6 + ifd_length)
  56. + b"MPF\0"
  57. + b" " * ifd_length
  58. )
  59. if exif := im_frame.encoderinfo.get("exif"):
  60. if isinstance(exif, Image.Exif):
  61. exif = exif.tobytes()
  62. im_frame.encoderinfo["exif"] = exif
  63. mpf_offset += 4 + len(exif)
  64. JpegImagePlugin._save(im_frame, fp, filename)
  65. offsets.append(fp.tell())
  66. else:
  67. encoderinfo = im_frame._attach_default_encoderinfo(im)
  68. im_frame.save(fp, "JPEG")
  69. im_frame.encoderinfo = encoderinfo
  70. offsets.append(fp.tell() - offsets[-1])
  71. ifd = TiffImagePlugin.ImageFileDirectory_v2()
  72. ifd[0xB000] = b"0100"
  73. ifd[0xB001] = len(offsets)
  74. mpentries = b""
  75. data_offset = 0
  76. for i, size in enumerate(offsets):
  77. if i == 0:
  78. mptype = 0x030000 # Baseline MP Primary Image
  79. else:
  80. mptype = 0x000000 # Undefined
  81. mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)
  82. if i == 0:
  83. data_offset -= mpf_offset
  84. data_offset += size
  85. ifd[0xB002] = mpentries
  86. fp.seek(mpf_offset)
  87. fp.write(b"II\x2a\x00" + o32le(8) + ifd.tobytes(8))
  88. fp.seek(0, os.SEEK_END)
  89. ##
  90. # Image plugin for MPO images.
  91. class MpoImageFile(JpegImagePlugin.JpegImageFile):
  92. format = "MPO"
  93. format_description = "MPO (CIPA DC-007)"
  94. _close_exclusive_fp_after_loading = False
  95. def _open(self) -> None:
  96. assert self.fp is not None
  97. self.fp.seek(0) # prep the fp in order to pass the JPEG test
  98. JpegImagePlugin.JpegImageFile._open(self)
  99. self._after_jpeg_open()
  100. def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:
  101. self.mpinfo = mpheader if mpheader is not None else self._getmp()
  102. if self.mpinfo is None:
  103. msg = "Image appears to be a malformed MPO file"
  104. raise ValueError(msg)
  105. self.n_frames = self.mpinfo[0xB001]
  106. self.__mpoffsets = [
  107. mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
  108. ]
  109. self.__mpoffsets[0] = 0
  110. # Note that the following assertion will only be invalid if something
  111. # gets broken within JpegImagePlugin.
  112. assert self.n_frames == len(self.__mpoffsets)
  113. del self.info["mpoffset"] # no longer needed
  114. self.is_animated = self.n_frames > 1
  115. assert self.fp is not None
  116. self._fp = self.fp # FIXME: hack
  117. self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
  118. self.__frame = 0
  119. self.offset = 0
  120. # for now we can only handle reading and individual frame extraction
  121. self.readonly = 1
  122. def load_seek(self, pos: int) -> None:
  123. if isinstance(self._fp, DeferredError):
  124. raise self._fp.ex
  125. self._fp.seek(pos)
  126. def seek(self, frame: int) -> None:
  127. if not self._seek_check(frame):
  128. return
  129. if isinstance(self._fp, DeferredError):
  130. raise self._fp.ex
  131. self.fp = self._fp
  132. self.offset = self.__mpoffsets[frame]
  133. original_exif = self.info.get("exif")
  134. if "exif" in self.info:
  135. del self.info["exif"]
  136. self.fp.seek(self.offset + 2) # skip SOI marker
  137. if not self.fp.read(2):
  138. msg = "No data found for frame"
  139. raise ValueError(msg)
  140. self.fp.seek(self.offset)
  141. JpegImagePlugin.JpegImageFile._open(self)
  142. Image._decompression_bomb_check(self.size)
  143. if self.info.get("exif") != original_exif:
  144. self._reload_exif()
  145. self.tile = [
  146. ImageFile._Tile("jpeg", (0, 0, *self.size), self.offset, self.tile[0][-1])
  147. ]
  148. self.__frame = frame
  149. Image.Image.seek(self, frame)
  150. def tell(self) -> int:
  151. return self.__frame
  152. @staticmethod
  153. def adopt(
  154. jpeg_instance: JpegImagePlugin.JpegImageFile,
  155. mpheader: dict[int, Any] | None = None,
  156. ) -> MpoImageFile:
  157. """
  158. Transform the instance of JpegImageFile into
  159. an instance of MpoImageFile.
  160. After the call, the JpegImageFile is extended
  161. to be an MpoImageFile.
  162. This is essentially useful when opening a JPEG
  163. file that reveals itself as an MPO, to avoid
  164. double call to _open.
  165. """
  166. jpeg_instance.__class__ = MpoImageFile
  167. mpo_instance = cast("MpoImageFile", jpeg_instance)
  168. mpo_instance._after_jpeg_open(mpheader)
  169. return mpo_instance
  170. # ---------------------------------------------------------------------
  171. # Registry stuff
  172. # Note that since MPO shares a factory with JPEG, we do not need to do a
  173. # separate registration for it here.
  174. # Image.register_open(MpoImageFile.format,
  175. # JpegImagePlugin.jpeg_factory, _accept)
  176. Image.register_save(MpoImageFile.format, _save)
  177. Image.register_save_all(MpoImageFile.format, _save_all)
  178. Image.register_extension(MpoImageFile.format, ".mpo")
  179. Image.register_mime(MpoImageFile.format, "image/mpo")