Modified ImageSequence Iterator class to be an iterator

This commit is contained in:
Andrew Murray 2016-01-06 21:09:40 +11:00
parent f57e295ce5
commit f4df96816b
2 changed files with 23 additions and 0 deletions

View File

@ -32,6 +32,7 @@ class Iterator(object):
if not hasattr(im, "seek"):
raise AttributeError("im must have seek method")
self.im = im
self.position = 0
def __getitem__(self, ix):
try:
@ -40,3 +41,17 @@ class Iterator(object):
return self.im
except EOFError:
raise IndexError # end of sequence
def __iter__(self):
return self
def __next__(self):
try:
self.im.seek(self.position)
self.position += 1
return self.im
except EOFError:
raise StopIteration
def next(self):
return self.__next__()

View File

@ -24,6 +24,14 @@ class TestImageSequence(PillowTestCase):
self.assertRaises(AttributeError, lambda: ImageSequence.Iterator(0))
def test_iterator(self):
im = Image.open('Tests/images/multipage.tiff')
i = ImageSequence.Iterator(im)
for index in range(0, im.n_frames):
self.assertEqual(i[index], next(i))
self.assertRaises(IndexError, lambda: i[index+1])
self.assertRaises(StopIteration, lambda: next(i))
def _test_multipage_tiff(self):
im = Image.open('Tests/images/multipage.tiff')
for index, frame in enumerate(ImageSequence.Iterator(im)):