MpoImagePlugin.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. import itertools
  22. import os
  23. import struct
  24. from typing import IO, Any, cast
  25. from . import (
  26. Image,
  27. ImageFile,
  28. ImageSequence,
  29. JpegImagePlugin,
  30. TiffImagePlugin,
  31. )
  32. from ._binary import o32le
  33. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  34. JpegImagePlugin._save(im, fp, filename)
  35. def _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  36. append_images = im.encoderinfo.get("append_images", [])
  37. if not append_images and not getattr(im, "is_animated", False):
  38. _save(im, fp, filename)
  39. return
  40. mpf_offset = 28
  41. offsets: list[int] = []
  42. for imSequence in itertools.chain([im], append_images):
  43. for im_frame in ImageSequence.Iterator(imSequence):
  44. if not offsets:
  45. # APP2 marker
  46. im_frame.encoderinfo["extra"] = (
  47. b"\xFF\xE2" + struct.pack(">H", 6 + 82) + b"MPF\0" + b" " * 82
  48. )
  49. exif = im_frame.encoderinfo.get("exif")
  50. if isinstance(exif, Image.Exif):
  51. exif = exif.tobytes()
  52. im_frame.encoderinfo["exif"] = exif
  53. if exif:
  54. mpf_offset += 4 + len(exif)
  55. JpegImagePlugin._save(im_frame, fp, filename)
  56. offsets.append(fp.tell())
  57. else:
  58. im_frame.save(fp, "JPEG")
  59. offsets.append(fp.tell() - offsets[-1])
  60. ifd = TiffImagePlugin.ImageFileDirectory_v2()
  61. ifd[0xB000] = b"0100"
  62. ifd[0xB001] = len(offsets)
  63. mpentries = b""
  64. data_offset = 0
  65. for i, size in enumerate(offsets):
  66. if i == 0:
  67. mptype = 0x030000 # Baseline MP Primary Image
  68. else:
  69. mptype = 0x000000 # Undefined
  70. mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)
  71. if i == 0:
  72. data_offset -= mpf_offset
  73. data_offset += size
  74. ifd[0xB002] = mpentries
  75. fp.seek(mpf_offset)
  76. fp.write(b"II\x2A\x00" + o32le(8) + ifd.tobytes(8))
  77. fp.seek(0, os.SEEK_END)
  78. ##
  79. # Image plugin for MPO images.
  80. class MpoImageFile(JpegImagePlugin.JpegImageFile):
  81. format = "MPO"
  82. format_description = "MPO (CIPA DC-007)"
  83. _close_exclusive_fp_after_loading = False
  84. def _open(self) -> None:
  85. self.fp.seek(0) # prep the fp in order to pass the JPEG test
  86. JpegImagePlugin.JpegImageFile._open(self)
  87. self._after_jpeg_open()
  88. def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:
  89. self.mpinfo = mpheader if mpheader is not None else self._getmp()
  90. if self.mpinfo is None:
  91. msg = "Image appears to be a malformed MPO file"
  92. raise ValueError(msg)
  93. self.n_frames = self.mpinfo[0xB001]
  94. self.__mpoffsets = [
  95. mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]
  96. ]
  97. self.__mpoffsets[0] = 0
  98. # Note that the following assertion will only be invalid if something
  99. # gets broken within JpegImagePlugin.
  100. assert self.n_frames == len(self.__mpoffsets)
  101. del self.info["mpoffset"] # no longer needed
  102. self.is_animated = self.n_frames > 1
  103. self._fp = self.fp # FIXME: hack
  104. self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame
  105. self.__frame = 0
  106. self.offset = 0
  107. # for now we can only handle reading and individual frame extraction
  108. self.readonly = 1
  109. def load_seek(self, pos: int) -> None:
  110. self._fp.seek(pos)
  111. def seek(self, frame: int) -> None:
  112. if not self._seek_check(frame):
  113. return
  114. self.fp = self._fp
  115. self.offset = self.__mpoffsets[frame]
  116. original_exif = self.info.get("exif")
  117. if "exif" in self.info:
  118. del self.info["exif"]
  119. self.fp.seek(self.offset + 2) # skip SOI marker
  120. if not self.fp.read(2):
  121. msg = "No data found for frame"
  122. raise ValueError(msg)
  123. self.fp.seek(self.offset)
  124. JpegImagePlugin.JpegImageFile._open(self)
  125. if self.info.get("exif") != original_exif:
  126. self._reload_exif()
  127. self.tile = [
  128. ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])
  129. ]
  130. self.__frame = frame
  131. def tell(self) -> int:
  132. return self.__frame
  133. @staticmethod
  134. def adopt(
  135. jpeg_instance: JpegImagePlugin.JpegImageFile,
  136. mpheader: dict[int, Any] | None = None,
  137. ) -> MpoImageFile:
  138. """
  139. Transform the instance of JpegImageFile into
  140. an instance of MpoImageFile.
  141. After the call, the JpegImageFile is extended
  142. to be an MpoImageFile.
  143. This is essentially useful when opening a JPEG
  144. file that reveals itself as an MPO, to avoid
  145. double call to _open.
  146. """
  147. jpeg_instance.__class__ = MpoImageFile
  148. mpo_instance = cast(MpoImageFile, jpeg_instance)
  149. mpo_instance._after_jpeg_open(mpheader)
  150. return mpo_instance
  151. # ---------------------------------------------------------------------
  152. # Registry stuff
  153. # Note that since MPO shares a factory with JPEG, we do not need to do a
  154. # separate registration for it here.
  155. # Image.register_open(MpoImageFile.format,
  156. # JpegImagePlugin.jpeg_factory, _accept)
  157. Image.register_save(MpoImageFile.format, _save)
  158. Image.register_save_all(MpoImageFile.format, _save_all)
  159. Image.register_extension(MpoImageFile.format, ".mpo")
  160. Image.register_mime(MpoImageFile.format, "image/mpo")