From 4fbea3e553d304544228dd7e7a215f772640b021 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 1 Jul 2015 09:18:05 +1000 Subject: [PATCH] Added multiframe GIF test --- PIL/GifImagePlugin.py | 27 +++++++++++++++++---------- Tests/test_file_gif.py | 10 ++++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py index 51fd11999..08567fcd0 100644 --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -299,9 +299,22 @@ RAWMODE = { "P": "P", } + +def _convert_mode(im): + # convert on the fly (EXPERIMENTAL -- I'm not sure PIL + # should automatically convert images on save...) + if Image.getmodebase(im.mode) == "RGB": + palette_size = 256 + if im.palette: + palette_size = len(im.palette.getdata()[1]) // 3 + return im.convert("P", palette=1, colors=palette_size) + return im.convert("L") + + def _save_all(im, fp, filename): _save(im, fp, filename, save_all=True) + def _save(im, fp, filename, save_all=False): if _imaging_gif: @@ -315,15 +328,7 @@ def _save(im, fp, filename, save_all=False): if im.mode in RAWMODE: im_out = im.copy() else: - # convert on the fly (EXPERIMENTAL -- I'm not sure PIL - # should automatically convert images on save...) - if Image.getmodebase(im.mode) == "RGB": - palette_size = 256 - if im.palette: - palette_size = len(im.palette.getdata()[1]) // 3 - im_out = im.convert("P", palette=1, colors=palette_size) - else: - im_out = im.convert("L") + im_out = _convert_mode(im) # header try: @@ -335,7 +340,9 @@ def _save(im, fp, filename, save_all=False): if save_all: previous = None - for im_frame in ImageSequence.Iterator(im_out): + for im_frame in ImageSequence.Iterator(im): + im_frame = _convert_mode(im_frame) + # To specify duration, add the time in milliseconds to getdata(), # e.g. getdata(im_frame, duration=1000) if not previous: diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 1141e0372..666e1f16d 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -72,6 +72,7 @@ class TestFileGif(PillowTestCase): self.assert_image_similar(reread.convert('RGB'), hopper(), 50) def test_roundtrip_save_all(self): + # Single frame image out = self.tempfile('temp.gif') im = hopper() im.save(out, save_all=True) @@ -79,6 +80,15 @@ class TestFileGif(PillowTestCase): self.assert_image_similar(reread.convert('RGB'), im, 50) + # Multiframe image + im = Image.open("Tests/images/dispose_bgnd.gif") + + out = self.tempfile('temp.gif') + im.save(out, save_all=True) + reread = Image.open(out) + + self.assertEqual(im.n_frames, 5) + def test_palette_handling(self): # see https://github.com/python-pillow/Pillow/issues/513