Animated images are really popular on the web right now, especially on sites like Tumblr and Reddit. So now and then you may see something in a tv show or movie you are watching and want to create a gif from it. Using python and 'images2gif' this is very easy and this is how.
This isn't needed, but I am going to assume you are running on Windows.
The plan is very simple. We are going to use FFMpeg to generate a series of screenshots from the video and then we are going resize them and stitch them together using "images2gif".
Setup the batch file to grab screenshots
FFMpeg is what we will be using to grab the screenshots and that can be called with a few command line instructions to get what we want out of it.
- -i : The video file we want to use
- -ss : The start time we want to begin.
- -f : Output type.
- -vframes: The number of frames we want to grab
- The last argument is the output directory and file name. The %%03d will be replace by the frame number so we have a sequential list.
Have a little play with this to get a feel for how it works and then put it into a batch file.
Calling the batch file from Python
Starting with a blank python file you will want to add code like this:
So that will write out the screenshots into a folder you have set in step one.
Using the images in python
Once the images are created you will want to load them like this
Resizing the images
This can be done using standard PIL functions like so:
Writing out the .gif file
This is where we use the "images2gif" to create a gif from our resized images.
I have set 0.0416 as the frame time as that is the time of one frame at 24fps. A lot of this could be controlled on input, or through a simple interface but that is a task for the reader.
This last bit of code will write out the .gif file for you to use. I would recommend playing with the settings and the size of the output image to find the desired quality and file size.
Here is all that code together with some input controls to make it easier to hook up and some cleanup at the end.
And here is a link of it all together: DOWNLOAD.
Next time I look at python I will show you how this can be combined to make easily make a .gif from Youtube and other web video sites and automatically upload them to Twitter or Tumblr.