Skip to content

Instantly share code, notes, and snippets.

@kersulis
Last active May 9, 2019 05:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kersulis/a5625582b71d1548899d7d8ca5054bd0 to your computer and use it in GitHub Desktop.
Save kersulis/a5625582b71d1548899d7d8ca5054bd0 to your computer and use it in GitHub Desktop.
jpg2gif

jpg2gif

Generate an animated GIF from a folder full of .jpg images.

1. Install prerequisites

You need:

  • Python 3; I used 3.6.2 for development and testing.
  • The imageio package. If you're using pip, install with pip install imageio. I worked with version 2.2.0.

2. Place your images

Make a folder called images in the same folder where this README is located. Fill this folder with the .jpg images you want to turn into an animation. Each image should be named with an integer that corresponds to its desired position in the GIF. In other words, the code will place 00.jpg before 01.jpg in the animation, and so on.

3. Run the code

Open the file makegif.py and check lines 7-10. You can change a few settings here:

  • outfile = 'output.gif' tells the code to put the output GIF in the same folder as the code, and call it "output.gif".
  • fps = 30 sets the animation speed to 30 frames per second. Feel free to change this.
  • The next two lines are used to crop the image. xrange = range(500,1310) tells the code to take only the pixel range from 500 to 1310 horizontally (0 corresponds to the left edge). yrange = range(360,1030) crops the image to the vertical range 360-1030 (where 0 corresponds to the top edge). If you do not want to crop, set either xrange or yrange to None.

Once you are satisfied with the settings, run the following:

python makegif.py

You should see messages communicating the code's progress. GIF generation should take around 30-45 seconds for one thousand input images that are each 250kB large. The resulting GIF should be about 2MB in size, provided that only a small part of each frame changes during the animation.

import sys, os
import imageio
def find_files(folder):
files = []
for file_name in os.listdir(folder):
if file_name.endswith('.jpg'):
path = os.path.join(folder, file_name)
idx = int(os.path.splitext(file_name)[0])
files.append((os.path.join(folder, file_name), idx))
sorted_files = [file[0] for file in sorted(files, key=lambda f:f[1])]
return sorted_files
def jpg2gif(jpg_folder, outfile='output.gif',
fps=30, xrange=None, yrange=None):
# Load all images into system memory.
# This should take no longer than 20s.
frames = []
paths = find_files(jpg_folder)
n = len(paths)
print("Loading %i images from '%s':" % (n,jpg_folder))
for i, path in enumerate(paths):
# read single image, add to stack
im = imageio.imread(path)
# crop image if pixel ranges were set
if (not xrange == None) and (not yrange == None):
im = im[:,xrange,:][yrange,:,:]
frames.append(im)
# update status bar
pct = round(100*i/n)
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-50s] %d%%" % ('='*round(pct/2), pct))
sys.stdout.flush()
# Save frames as gif, takes several more seconds
print('\nWriting GIF...')
kargs = { 'fps': fps, 'subrectangles': True }
imageio.mimsave(outfile, frames, 'GIF', **kargs)
print("Done: %s generated in folder '%s'." % (outfile, os.getcwd()))
import os
from jpg2gif_functions import jpg2gif
# assume all images are in a folder called images,
# nested under the folder where this code is.
jpg_folder = os.path.join(os.getcwd(),'images')
outfile = 'output.gif'
fps = 30 # change the fps here
xrange = range(500,1310) # horizontal pixel range
yrange = range(360,1030) # vertical pixel range
# generate gif:
jpg2gif(jpg_folder, outfile=outfile,
fps=fps, xrange=xrange, yrange=yrange)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment