Skip to content

Commit beb7b4d

Browse files
committed
Added reading of TIFF child images
1 parent d843759 commit beb7b4d

5 files changed

Lines changed: 51 additions & 0 deletions

File tree

Tests/images/child_ifd.tiff

2.9 KB
Binary file not shown.

Tests/images/child_ifd_jpeg.tiff

830 Bytes
Binary file not shown.

Tests/test_file_tiff.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@ def test_context_manager(self):
8484
with Image.open("Tests/images/multipage.tiff") as im:
8585
im.load()
8686

87+
def test_get_child_images(self):
88+
def check(ims, sizes):
89+
assert len(ims) == len(sizes)
90+
91+
for i, im in enumerate(ims):
92+
w = sizes[i]
93+
expected = Image.new("RGB", (w, w), "#f00")
94+
assert_image_similar(im, expected, 1)
95+
96+
with Image.open("Tests/images/child_ifd.tiff") as im:
97+
ims = im.get_child_images()
98+
check(ims, (16, 8))
99+
100+
with Image.open("Tests/images/child_ifd_jpeg.tiff") as im:
101+
ims = im.get_child_images()
102+
check(ims, (20,))
103+
87104
def test_mac_tiff(self):
88105
# Read RGBa images from macOS [@PIL136]
89106

src/PIL/TiffImagePlugin.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,39 @@ def tell(self):
11481148
"""Return the current frame number"""
11491149
return self.__frame
11501150

1151+
def get_child_images(self):
1152+
if SUBIFD not in self.tag_v2:
1153+
return []
1154+
child_images = []
1155+
exif = self.getexif()
1156+
offset = None
1157+
for im_offset in self.tag_v2[SUBIFD]:
1158+
# reset buffered io handle in case fp
1159+
# was passed to libtiff, invalidating the buffer
1160+
current_offset = self._fp.tell()
1161+
if offset is None:
1162+
offset = current_offset
1163+
1164+
fp = self._fp
1165+
ifd = exif._get_ifd_dict(im_offset)
1166+
jpegInterchangeFormat = ifd.get(513)
1167+
if jpegInterchangeFormat is not None:
1168+
fp.seek(jpegInterchangeFormat)
1169+
jpeg_data = fp.read(ifd.get(514))
1170+
1171+
fp = io.BytesIO(jpeg_data)
1172+
1173+
with Image.open(fp) as im:
1174+
if jpegInterchangeFormat is None:
1175+
im._frame_pos = [im_offset]
1176+
im._seek(0)
1177+
im.load()
1178+
child_images.append(im)
1179+
1180+
if offset is not None:
1181+
self._fp.seek(offset)
1182+
return child_images
1183+
11511184
def getxmp(self):
11521185
"""
11531186
Returns a dictionary containing the XMP tags.

src/PIL/TiffTags.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ def lookup(tag, group=None):
160160
323: ("TileLength", LONG, 1),
161161
324: ("TileOffsets", LONG, 0),
162162
325: ("TileByteCounts", LONG, 0),
163+
330: ("SubIFDs", LONG, 0),
163164
332: ("InkSet", SHORT, 1),
164165
333: ("InkNames", ASCII, 1),
165166
334: ("NumberOfInks", SHORT, 1),

0 commit comments

Comments
 (0)