FpxImagePlugin.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #
  2. # THIS IS WORK IN PROGRESS
  3. #
  4. # The Python Imaging Library.
  5. # $Id$
  6. #
  7. # FlashPix support for PIL
  8. #
  9. # History:
  10. # 97-01-25 fl Created (reads uncompressed RGB images only)
  11. #
  12. # Copyright (c) Secret Labs AB 1997.
  13. # Copyright (c) Fredrik Lundh 1997.
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. from __future__ import annotations
  18. __lazy_modules__ = {"PIL._binary"}
  19. import olefile
  20. from . import Image, ImageFile
  21. from ._binary import i32le as i32
  22. # we map from colour field tuples to (mode, rawmode) descriptors
  23. MODES = {
  24. # opacity
  25. (0x00007FFE,): ("A", "L"),
  26. # monochrome
  27. (0x00010000,): ("L", "L"),
  28. (0x00018000, 0x00017FFE): ("RGBA", "LA"),
  29. # photo YCC
  30. (0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
  31. (0x00028000, 0x00028001, 0x00028002, 0x00027FFE): ("RGBA", "YCCA;P"),
  32. # standard RGB (NIFRGB)
  33. (0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
  34. (0x00038000, 0x00038001, 0x00038002, 0x00037FFE): ("RGBA", "RGBA"),
  35. }
  36. #
  37. # --------------------------------------------------------------------
  38. def _accept(prefix: bytes) -> bool:
  39. return prefix.startswith(olefile.MAGIC)
  40. ##
  41. # Image plugin for the FlashPix images.
  42. class FpxImageFile(ImageFile.ImageFile):
  43. format = "FPX"
  44. format_description = "FlashPix"
  45. def _open(self) -> None:
  46. #
  47. # read the OLE directory and see if this is a likely
  48. # to be a FlashPix file
  49. assert self.fp is not None
  50. try:
  51. self.ole = olefile.OleFileIO(self.fp)
  52. except OSError as e:
  53. msg = "not an FPX file; invalid OLE file"
  54. raise SyntaxError(msg) from e
  55. root = self.ole.root
  56. if not root or root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
  57. msg = "not an FPX file; bad root CLSID"
  58. raise SyntaxError(msg)
  59. self._open_index(1)
  60. def _open_index(self, index: int = 1) -> None:
  61. #
  62. # get the Image Contents Property Set
  63. prop = self.ole.getproperties(
  64. [f"Data Object Store {index:06d}", "\005Image Contents"]
  65. )
  66. # size (highest resolution)
  67. assert isinstance(prop[0x1000002], int)
  68. assert isinstance(prop[0x1000003], int)
  69. self._size = prop[0x1000002], prop[0x1000003]
  70. size = max(self.size)
  71. i = 1
  72. while size > 64:
  73. size = size // 2
  74. i += 1
  75. self.maxid = i - 1
  76. # mode. instead of using a single field for this, flashpix
  77. # requires you to specify the mode for each channel in each
  78. # resolution subimage, and leaves it to the decoder to make
  79. # sure that they all match. for now, we'll cheat and assume
  80. # that this is always the case.
  81. id = self.maxid << 16
  82. s = prop[0x2000002 | id]
  83. if not isinstance(s, bytes) or (bands := i32(s, 4)) > 4:
  84. msg = "Invalid number of bands"
  85. raise OSError(msg)
  86. # note: for now, we ignore the "uncalibrated" flag
  87. colors = tuple(i32(s, 8 + i * 4) & 0x7FFFFFFF for i in range(bands))
  88. self._mode, self.rawmode = MODES[colors]
  89. # load JPEG tables, if any
  90. self.jpeg = {}
  91. for i in range(256):
  92. id = 0x3000001 | (i << 16)
  93. if id in prop:
  94. self.jpeg[i] = prop[id]
  95. self._open_subimage(1, self.maxid)
  96. def _open_subimage(self, index: int = 1, subimage: int = 0) -> None:
  97. #
  98. # setup tile descriptors for a given subimage
  99. stream = [
  100. f"Data Object Store {index:06d}",
  101. f"Resolution {subimage:04d}",
  102. "Subimage 0000 Header",
  103. ]
  104. fp = self.ole.openstream(stream)
  105. # skip prefix
  106. fp.read(28)
  107. # header stream
  108. s = fp.read(36)
  109. size = i32(s, 4), i32(s, 8)
  110. # tilecount = i32(s, 12)
  111. xtile, ytile = i32(s, 16), i32(s, 20)
  112. if xtile != 64 or ytile != 64:
  113. msg = "Tile must be 64 pixels by 64 pixels"
  114. raise ValueError(msg)
  115. # channels = i32(s, 24)
  116. offset = i32(s, 28)
  117. length = i32(s, 32)
  118. if size != self.size:
  119. msg = "subimage mismatch"
  120. raise OSError(msg)
  121. # get tile descriptors
  122. fp.seek(28 + offset)
  123. s = fp.read(i32(s, 12) * length)
  124. x = y = 0
  125. xsize, ysize = size
  126. self.tile = []
  127. for i in range(0, len(s), length):
  128. x1 = min(xsize, x + xtile)
  129. y1 = min(ysize, y + ytile)
  130. compression = i32(s, i + 8)
  131. if compression == 0:
  132. self.tile.append(
  133. ImageFile._Tile(
  134. "raw",
  135. (x, y, x1, y1),
  136. i32(s, i) + 28,
  137. self.rawmode,
  138. )
  139. )
  140. elif compression == 1:
  141. # FIXME: the fill decoder is not implemented
  142. self.tile.append(
  143. ImageFile._Tile(
  144. "fill",
  145. (x, y, x1, y1),
  146. i32(s, i) + 28,
  147. (self.rawmode, s[12:16]),
  148. )
  149. )
  150. elif compression == 2:
  151. internal_color_conversion = s[14]
  152. jpeg_tables = s[15]
  153. rawmode = self.rawmode
  154. if internal_color_conversion:
  155. # The image is stored as usual (usually YCbCr).
  156. if rawmode == "RGBA":
  157. # For "RGBA", data is stored as YCbCrA based on
  158. # negative RGB. The following trick works around
  159. # this problem :
  160. jpegmode, rawmode = "YCbCrK", "CMYK"
  161. else:
  162. jpegmode = None # let the decoder decide
  163. else:
  164. # The image is stored as defined by rawmode
  165. jpegmode = rawmode
  166. self.tile.append(
  167. ImageFile._Tile(
  168. "jpeg",
  169. (x, y, x1, y1),
  170. i32(s, i) + 28,
  171. (rawmode, jpegmode),
  172. )
  173. )
  174. # FIXME: jpeg tables are tile dependent; the prefix
  175. # data must be placed in the tile descriptor itself!
  176. if jpeg_tables:
  177. self.tile_prefix = self.jpeg[jpeg_tables]
  178. else:
  179. msg = "unknown/invalid compression"
  180. raise OSError(msg)
  181. x += xtile
  182. if x >= xsize:
  183. x, y = 0, y + ytile
  184. if y >= ysize:
  185. break # isn't really required
  186. assert self.fp is not None
  187. self.stream = stream
  188. self._fp = self.fp
  189. self.fp = None
  190. def load(self) -> Image.core.PixelAccess | None:
  191. if not self.fp:
  192. self.fp = self.ole.openstream(self.stream[:2] + ["Subimage 0000 Data"])
  193. return ImageFile.ImageFile.load(self)
  194. def close(self) -> None:
  195. self.ole.close()
  196. super().close()
  197. def __exit__(self, *args: object) -> None:
  198. self.ole.close()
  199. super().__exit__()
  200. #
  201. # --------------------------------------------------------------------
  202. Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
  203. Image.register_extension(FpxImageFile.format, ".fpx")