Search code examples
python-3.xfor-loopappendpython-imaging-libraryglob

Why does this for loop have an i counter that jumps from 1 to 10 when appending images on Python? PIL related


I have the following images at some specific path:

0.png
1.png
2.png
3.png
4.png
5.png
6.png
7.png
8.png
9.png
10.png
11.png
12.png
13.png
14.png
15.png
16.png
17.png
18.png
19.png
20.png
21.png
22.png
23.png
24.png
25.png
26.png

And I want to use the following program (which is located at the same specific path the images are located) to convert those images to a single gif file

from PIL import Image
import glob

# Create the frames
frames = []
imgs = glob.glob("*.png")
for i in imgs:
    new_frame = Image.open(i)
    frames.append(new_frame)
    print(i)

# Save into a GIF file that loops forever
frames[0].save('png_to_gif.gif', format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=160, loop=0)

After running the program above I got this output:

0.png
1.png
10.png
11.png
12.png
13.png
14.png
15.png
16.png
17.png
18.png
19.png
2.png
20.png
21.png
22.png
23.png
24.png
25.png
26.png
3.png
4.png
5.png
6.png
7.png
8.png
9.png

How can I assure that the order in which the program will append the images will be the same order in which they were named?


Solution

  • I decided to modify the code this way, it seems to work for the moment, if there's a way in which I can just create an array to store only the filenames that end with .png for a given path, it's welcome:

    from PIL import Image
    
    
    # Create the frames
    frames = []
    imgs = ["0.png", "1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png", "10.png", "11.png", "12.png", "13.png", "14.png", "15.png", "16.png", "17.png", "18.png", "19.png", "20.png", "21.png", "22.png", "23.png", "24.png", "25.png", "26.png"]
    for i in imgs:
        new_frame = Image.open(i)
        frames.append(new_frame)
        print(i)
    
    # Save into a GIF file that loops forever
    frames[0].save('png_to_gif.gif', format='GIF',
                   append_images=frames[1:],
                   save_all=True,
                   duration=180, loop=0)