Reputation: 91
I'm trying to modify GIFs, by first reading them in, parsing the individual images into an array, adding some duplicate copies of the last frame to the array, and then resaving them as a GIF. I'm able to get it to work but it saves in like negative black and white color. What am I doing wrong?
Here's my code:
from PIL import Image
from PIL import GifImagePlugin
from PIL import ImageSequence
import imageio
imageObject = Image.open(directory+gif_path)
frames = [frame.copy() for frame in ImageSequence.Iterator(imageObject)]
ending_frame = frames[-1].copy()
for val in range(5):
frames.append(ending_frame)
imageio.mimsave('new.gif',frames)
I suspect it has to do with the way Pillow processes RGB values versus the way imageio processes them? If that's the case, how do I save an array of Pillow images to a GIF using Pillow itself? This is what the first few instances of the array "frames" looks like:
[<PIL.Image.Image image mode=P size=720x360 at 0x2661F2F50A0>,
<PIL.Image.Image image mode=P size=720x360 at 0x2661F4A7BE0>,
<PIL.Image.Image image mode=P size=720x360 at 0x2661F4B3250>,
<PIL.Image.Image image mode=P size=720x360 at 0x2661F4B3820>,
<PIL.Image.Image image mode=P size=720x360 at 0x2661F4B38E0>,
<PIL.Image.Image image mode=P size=720x360 at 0x2661F4B3970>]
Upvotes: 1
Views: 2771
Reputation: 491
Pillow has all you need to make a gif in the save method. Use glob to get all the images from some folder.
from PIL import Image
import glob
image_list = []
# save images in directory to list
for filename in glob.glob('yourpath/*.png'): # change ending to jpg or jpeg is using those image formats
im=Image.open(filename)
image_list.append(im)
# save image list as a gif (ordered alphabetically by glob)
image_list[0].save("yourpath/newGif.gif", save_all=True, append_images=image_list[1:], optimize=False, duration=40, loop=0)
edit: for modifying gifs and resaving as a gif
rom PIL import Image, ImageSequence
# Opening the input gif:
im = Image.open("animation.gif")
# create an empty list to store the frames
frames = []
# iterate over the frames of the gif as save
for frame in ImageSequence.Iterator(im):
frames.append(frame)
# add last frame some amount of times
for i in range(3):
frames.append(frames[-1])
# save as new gif
frames[0].save("yourpath/newGif.gif", save_all=True, append_images=frames[1:], optimize=False, duration=40, loop=0)
Upvotes: 3