IptcImagePlugin.py 6.3 KB

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