diff --git a/PIL/ImageSequence.py b/PIL/ImageSequence.py index 256bcbedb..76bc2d826 100644 --- a/PIL/ImageSequence.py +++ b/PIL/ImageSequence.py @@ -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__() diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py index 9e18192ee..3e30b3ca3 100644 --- a/Tests/test_imagesequence.py +++ b/Tests/test_imagesequence.py @@ -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)):