can pass list of integer to set different duration for each frame when saving GIF

This commit is contained in:
Xinyi Rong 2016-12-22 01:09:02 +08:00
parent 954fc52877
commit 8f44fa4aec
3 changed files with 44 additions and 12 deletions

View File

@ -352,10 +352,21 @@ 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 duration is not None:
if not isinstance(duration, list):
encoderinfo["duration"] = duration
else:
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)

View File

@ -281,6 +281,25 @@ 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

View File

@ -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 integer. Passing a list to ``duration`` parameter
will set the ``duration`` of each frame respectively.
Reading local images
~~~~~~~~~~~~~~~~~~~~