Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/IptcImagePlugin.py: 38%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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#
17from __future__ import annotations
19__lazy_modules__ = {"PIL._binary", "io", "typing"}
21from io import BytesIO
22from typing import cast
24from . import Image, ImageFile
25from ._binary import i16be as i16
26from ._binary import i32be as i32
28COMPRESSION = {1: "raw", 5: "jpeg"}
31#
32# Helpers
35def _i(c: bytes) -> int:
36 return i32((b"\0\0\0\0" + c)[-4:])
39##
40# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
41# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
44class IptcImageFile(ImageFile.ImageFile):
45 format = "IPTC"
46 format_description = "IPTC/NAA"
48 def getint(self, key: tuple[int, int]) -> int:
49 return _i(self.info[key])
51 def field(self) -> tuple[tuple[int, int] | None, int]:
52 #
53 # get a IPTC field header
54 assert self.fp is not None
55 s = self.fp.read(5)
56 if not s.strip(b"\x00"):
57 return None, 0
59 tag = s[1], s[2]
61 # syntax
62 if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:
63 msg = "invalid IPTC/NAA file"
64 raise SyntaxError(msg)
66 # field size
67 size = s[3]
68 if size > 132:
69 msg = "illegal field length in IPTC/NAA file"
70 raise OSError(msg)
71 elif size == 128:
72 size = 0
73 elif size > 128:
74 size = _i(self.fp.read(size - 128))
75 else:
76 size = i16(s, 3)
78 return tag, size
80 def _open(self) -> None:
81 # load descriptive fields
82 assert self.fp is not None
83 while True:
84 offset = self.fp.tell()
85 tag, size = self.field()
86 if not tag or tag == (8, 10):
87 break
88 if size:
89 tagdata = self.fp.read(size)
90 else:
91 tagdata = None
92 if tag in self.info:
93 if isinstance(self.info[tag], list):
94 self.info[tag].append(tagdata)
95 else:
96 self.info[tag] = [self.info[tag], tagdata]
97 else:
98 self.info[tag] = tagdata
100 # mode
101 layers = self.info[(3, 60)][0]
102 component = self.info[(3, 60)][1]
103 if layers == 1 and not component:
104 self._mode = "L"
105 band = None
106 else:
107 if layers == 3 and component:
108 self._mode = "RGB"
109 elif layers == 4 and component:
110 self._mode = "CMYK"
111 if (3, 65) in self.info:
112 band = self.info[(3, 65)][0] - 1
113 else:
114 band = 0
116 # size
117 self._size = self.getint((3, 20)), self.getint((3, 30))
119 # compression
120 try:
121 compression = COMPRESSION[self.getint((3, 120))]
122 except KeyError as e:
123 msg = "Unknown IPTC image compression"
124 raise OSError(msg) from e
126 # tile
127 if tag == (8, 10):
128 self.tile = [ImageFile._Tile("iptc", None, offset, (compression, band))]
130 def load(self) -> Image.core.PixelAccess | None:
131 if self.tile:
132 args = self.tile[0].args
133 assert isinstance(args, tuple)
134 compression, band = args
136 assert self.fp is not None
137 self.fp.seek(self.tile[0].offset)
139 # Copy image data to temporary file
140 o = BytesIO()
141 if compression == "raw":
142 # To simplify access to the extracted file,
143 # prepend a PPM header
144 o.write(b"P5\n%d %d\n255\n" % self.size)
145 while True:
146 type, size = self.field()
147 if type != (8, 10):
148 break
149 while size > 0:
150 s = self.fp.read(min(size, 8192))
151 if not s:
152 break
153 o.write(s)
154 size -= len(s)
156 with Image.open(o) as _im:
157 if band is not None:
158 bands = [Image.new("L", _im.size)] * Image.getmodebands(self.mode)
159 bands[band] = _im
160 im = Image.merge(self.mode, bands)
161 else:
162 im = _im
163 im.load()
164 self.im = im.im
165 self.tile = []
166 return ImageFile.ImageFile.load(self)
169Image.register_open(IptcImageFile.format, IptcImageFile)
171Image.register_extension(IptcImageFile.format, ".iim")
174def getiptcinfo(
175 im: ImageFile.ImageFile,
176) -> dict[tuple[int, int], bytes | list[bytes]] | None:
177 """
178 Get IPTC information from TIFF, JPEG, or IPTC file.
180 :param im: An image containing IPTC data.
181 :returns: A dictionary containing IPTC information, or None if
182 no IPTC information block was found.
183 """
184 from . import JpegImagePlugin, TiffImagePlugin
186 data = None
188 if isinstance(im, IptcImageFile):
189 # return info dictionary right away
190 return {k: v for k, v in im.info.items() if isinstance(k, tuple)}
192 elif isinstance(im, JpegImagePlugin.JpegImageFile):
193 # extract the IPTC/NAA resource
194 photoshop = im.info.get("photoshop")
195 if photoshop:
196 data = photoshop.get(0x0404)
198 elif isinstance(im, TiffImagePlugin.TiffImageFile):
199 # get raw data from the IPTC/NAA tag (PhotoShop tags the data
200 # as 4-byte integers, so we cannot use the get method...)
201 try:
202 data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
203 except KeyError:
204 pass
206 if data is None:
207 return None # no properties
209 # create an IptcImagePlugin object without initializing it
210 class FakeImage:
211 pass
213 fake_im = FakeImage()
214 fake_im.__class__ = IptcImageFile # type: ignore[assignment]
215 iptc_im = cast("IptcImageFile", fake_im)
217 # parse the IPTC information chunk
218 iptc_im.info = {}
219 iptc_im.fp = BytesIO(data)
221 try:
222 iptc_im._open()
223 except (IndexError, KeyError):
224 pass # expected failure
226 return {k: v for k, v in iptc_im.info.items() if isinstance(k, tuple)}