IptcImagePlugin.py 5.7 KB

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