IptcImagePlugin.py 5.6 KB

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