11

I have two GIF files, and I want to combine them horizontally to be shown beside each other, and they play together. They have equal frames. I tried a lot online for a solution, but didn't find something which is supporting GIF. I think the imageio package supports gif, but I can't find a way to use it to combine two together Simply, I want something like this example enter image description here Any ideas of doing so ?

Mostafa Hussein
  • 361
  • 4
  • 16

1 Answers1

4

I would code something like this :

import imageio
import numpy as np    

#Create reader object for the gif
gif1 = imageio.get_reader('file1.gif')
gif2 = imageio.get_reader('file2.gif')

#If they don't have the same number of frame take the shorter
number_of_frames = min(gif1.get_length(), gif2.get_length()) 

#Create writer object
new_gif = imageio.get_writer('output.gif')

for frame_number in range(number_of_frames):
    img1 = gif1.get_next_data()
    img2 = gif2.get_next_data()
    #here is the magic
    new_image = np.hstack((img1, img2))
    new_gif.append_data(new_image)

gif1.close()
gif2.close()    
new_gif.close()

So the magic trick is to use the hstack numpy function. It will basically stack them horizontally. This only work if the two gif are the same dimensions.

Ozan Kurt
  • 3,731
  • 4
  • 18
  • 32
rponthieu dev
  • 126
  • 1
  • 9
  • 1
    `imageio` cannot write transparency layers to GIFs, which is what bit me. Stay away if you need that! – xjcl Jan 14 '20 at 06:11