IptcImagePlugin.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # IPTC/NAA file handling
  6. #
  7. # history:
  8. # 1995-10-01 fl Created
  9. # 1998-03-09 fl Cleaned up and added to PIL
  10. # 2002-06-18 fl Added getiptcinfo helper
  11. #
  12. # Copyright (c) Secret Labs AB 1997-2002.
  13. # Copyright (c) Fredrik Lundh 1995.
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. from __future__ import annotations
  18. from collections.abc import Sequence
  19. from io import BytesIO
  20. from typing import cast
  21. from . import Image, ImageFile
  22. from ._binary import i16be as i16
  23. from ._binary import i32be as i32
  24. from ._deprecate import deprecate
  25. COMPRESSION = {1: "raw", 5: "jpeg"}
  26. def __getattr__(name: str) -> bytes:
  27. if name == "PAD":
  28. deprecate("IptcImagePlugin.PAD", 12)
  29. return b"\0\0\0\0"
  30. msg = f"module '{__name__}' has no attribute '{name}'"
  31. raise AttributeError(msg)
  32. #
  33. # Helpers
  34. def _i(c: bytes) -> int:
  35. return i32((b"\0\0\0\0" + c)[-4:])
  36. def _i8(c: int | bytes) -> int:
  37. return c if isinstance(c, int) else c[0]
  38. def i(c: bytes) -> int:
  39. """.. deprecated:: 10.2.0"""
  40. deprecate("IptcImagePlugin.i", 12)
  41. return _i(c)
  42. def dump(c: Sequence[int | bytes]) -> None:
  43. """.. deprecated:: 10.2.0"""
  44. deprecate("IptcImagePlugin.dump", 12)
  45. for i in c:
  46. print(f"{_i8(i):02x}", end=" ")
  47. print()
  48. ##
  49. # Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
  50. # from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
  51. class IptcImageFile(ImageFile.ImageFile):
  52. format = "IPTC"
  53. format_description = "IPTC/NAA"
  54. def getint(self, key: tuple[int, int]) -> int:
  55. return _i(self.info[key])
  56. def field(self) -> tuple[tuple[int, int] | None, int]:
  57. #
  58. # get a IPTC field header
  59. s = self.fp.read(5)
  60. if not s.strip(b"\x00"):
  61. return None, 0
  62. tag = s[1], s[2]
  63. # syntax
  64. if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:
  65. msg = "invalid IPTC/NAA file"
  66. raise SyntaxError(msg)
  67. # field size
  68. size = s[3]
  69. if size > 132:
  70. msg = "illegal field length in IPTC/NAA file"
  71. raise OSError(msg)
  72. elif size == 128:
  73. size = 0
  74. elif size > 128:
  75. size = _i(self.fp.read(size - 128))
  76. else:
  77. size = i16(s, 3)
  78. return tag, size
  79. def _open(self) -> None:
  80. # load descriptive fields
  81. while True:
  82. offset = self.fp.tell()
  83. tag, size = self.field()
  84. if not tag or tag == (8, 10):
  85. break
  86. if size:
  87. tagdata = self.fp.read(size)
  88. else:
  89. tagdata = None
  90. if tag in self.info:
  91. if isinstance(self.info[tag], list):
  92. self.info[tag].append(tagdata)
  93. else:
  94. self.info[tag] = [self.info[tag], tagdata]
  95. else:
  96. self.info[tag] = tagdata
  97. # mode
  98. layers = self.info[(3, 60)][0]
  99. component = self.info[(3, 60)][1]
  100. if (3, 65) in self.info:
  101. id = self.info[(3, 65)][0] - 1
  102. else:
  103. id = 0
  104. if layers == 1 and not component:
  105. self._mode = "L"
  106. elif layers == 3 and component:
  107. self._mode = "RGB"[id]
  108. elif layers == 4 and component:
  109. self._mode = "CMYK"[id]
  110. # size
  111. self._size = self.getint((3, 20)), self.getint((3, 30))
  112. # compression
  113. try:
  114. compression = COMPRESSION[self.getint((3, 120))]
  115. except KeyError as e:
  116. msg = "Unknown IPTC image compression"
  117. raise OSError(msg) from e
  118. # tile
  119. if tag == (8, 10):
  120. self.tile = [
  121. ImageFile._Tile("iptc", (0, 0) + self.size, offset, compression)
  122. ]
  123. def load(self) -> Image.core.PixelAccess | None:
  124. if len(self.tile) != 1 or self.tile[0][0] != "iptc":
  125. return ImageFile.ImageFile.load(self)
  126. offset, compression = self.tile[0][2:]
  127. self.fp.seek(offset)
  128. # Copy image data to temporary file
  129. o = BytesIO()
  130. if compression == "raw":
  131. # To simplify access to the extracted file,
  132. # prepend a PPM header
  133. o.write(b"P5\n%d %d\n255\n" % self.size)
  134. while True:
  135. type, size = self.field()
  136. if type != (8, 10):
  137. break
  138. while size > 0:
  139. s = self.fp.read(min(size, 8192))
  140. if not s:
  141. break
  142. o.write(s)
  143. size -= len(s)
  144. with Image.open(o) as _im:
  145. _im.load()
  146. self.im = _im.im
  147. return None
  148. Image.register_open(IptcImageFile.format, IptcImageFile)
  149. Image.register_extension(IptcImageFile.format, ".iim")
  150. def getiptcinfo(
  151. im: ImageFile.ImageFile,
  152. ) -> dict[tuple[int, int], bytes | list[bytes]] | None:
  153. """
  154. Get IPTC information from TIFF, JPEG, or IPTC file.
  155. :param im: An image containing IPTC data.
  156. :returns: A dictionary containing IPTC information, or None if
  157. no IPTC information block was found.
  158. """
  159. from . import JpegImagePlugin, TiffImagePlugin
  160. data = None
  161. info: dict[tuple[int, int], bytes | list[bytes]] = {}
  162. if isinstance(im, IptcImageFile):
  163. # return info dictionary right away
  164. for k, v in im.info.items():
  165. if isinstance(k, tuple):
  166. info[k] = v
  167. return info
  168. elif isinstance(im, JpegImagePlugin.JpegImageFile):
  169. # extract the IPTC/NAA resource
  170. photoshop = im.info.get("photoshop")
  171. if photoshop:
  172. data = photoshop.get(0x0404)
  173. elif isinstance(im, TiffImagePlugin.TiffImageFile):
  174. # get raw data from the IPTC/NAA tag (PhotoShop tags the data
  175. # as 4-byte integers, so we cannot use the get method...)
  176. try:
  177. data = im.tag_v2[TiffImagePlugin.IPTC_NAA_CHUNK]
  178. except KeyError:
  179. pass
  180. if data is None:
  181. return None # no properties
  182. # create an IptcImagePlugin object without initializing it
  183. class FakeImage:
  184. pass
  185. fake_im = FakeImage()
  186. fake_im.__class__ = IptcImageFile # type: ignore[assignment]
  187. iptc_im = cast(IptcImageFile, fake_im)
  188. # parse the IPTC information chunk
  189. iptc_im.info = {}
  190. iptc_im.fp = BytesIO(data)
  191. try:
  192. iptc_im._open()
  193. except (IndexError, KeyError):
  194. pass # expected failure
  195. for k, v in iptc_im.info.items():
  196. if isinstance(k, tuple):
  197. info[k] = v
  198. return info