IptcImagePlugin.py 6.3 KB

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