From 87092ad4f8e55444ec3134ed857e4de5d19cd175 Mon Sep 17 00:00:00 2001 From: wiredfool Date: Tue, 27 Dec 2016 02:42:58 -0800 Subject: [PATCH] can pass list of integer to set different duration for each frame when saving GIF --- PIL/GifImagePlugin.py | 8 ++++++++ Tests/test_file_gif.py | 24 ++++++++++++++++++++++++ docs/handbook/image-file-formats.rst | 4 +++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/PIL/GifImagePlugin.py b/PIL/GifImagePlugin.py index 2775a00f1..60d6f49e4 100644 --- a/PIL/GifImagePlugin.py +++ b/PIL/GifImagePlugin.py @@ -352,10 +352,18 @@ def _save(im, fp, filename, save_all=False): first_frame = None append_images = im.encoderinfo.get("append_images", []) + if "duration" in im.encoderinfo: + duration = im.encoderinfo["duration"] + else: + duration = None + frame_count = 0 for imSequence in [im]+append_images: for im_frame in ImageSequence.Iterator(imSequence): encoderinfo = im.encoderinfo.copy() im_frame = _convert_mode(im_frame) + if isinstance(duration, list): + encoderinfo["duration"] = duration[frame_count] + frame_count += 1 # To specify duration, add the time in milliseconds to getdata(), # e.g. getdata(im_frame, duration=1000) diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py index 1672a14f0..fdc7d9d55 100644 --- a/Tests/test_file_gif.py +++ b/Tests/test_file_gif.py @@ -281,6 +281,30 @@ class TestFileGif(PillowTestCase): self.assertEqual(reread.info['duration'], duration) + def test_multiple_duration(self): + duration_list = [1000, 2000, 3000] + + out = self.tempfile('temp.gif') + im_list = [ + Image.new('L', (100, 100), '#000'), + Image.new('L', (100, 100), '#111'), + Image.new('L', (100, 100), '#222'), + ] + im_list[0].save( + out, + save_all=True, + append_images=im_list[1:], + duration=duration_list + ) + reread = Image.open(out) + + for duration in duration_list: + self.assertEqual(reread.info['duration'], duration) + try: + reread.seek(reread.tell() + 1) + except EOFError: + pass + def test_number_of_loops(self): number_of_loops = 2 diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst index 11486c76b..36513efd5 100644 --- a/docs/handbook/image-file-formats.rst +++ b/docs/handbook/image-file-formats.rst @@ -111,7 +111,9 @@ additional frames when saving, the ``append_images`` parameter works with If present, the ``loop`` parameter can be used to set the number of times the GIF should loop, and the ``duration`` parameter can set the number of -milliseconds between each frame. +milliseconds between each frame. The ``duration`` parameter can be either an +integer or a list of integers. Passing a list to the ``duration``parameter +will set the ``duration`` of each frame respectively. Reading local images ~~~~~~~~~~~~~~~~~~~~