When creating a GIF using imageio the resulting images can get quite heavy, as the created GIF is not optimized. This can be useful when the elaboration process for the GIF is not finished yet (for instance if some elaboration on specific frames stills need to happen), but it can be an issue when the process is finished and the GIF is unexpectedly big.
GIF files can be compressed in several ways, the most common one method (the one used here) is saving just the differences between the following frames. In this example, we apply the described method to a given GIF my_gif using pygifsicle, a porting of the general-purpose GIF editing command-line library gifsicle.
As usual, just download it using pip:
pip install pygifsicle
While running the installation, on MacOS the setup will automatically install gifsicle using [Brew](https://brew.sh/).
On Linux you will need to install gifsicle using apt-get as follows:
sudo apt-get install gifsicle
On Windows you will need to download and install the [correct port of the library](https://eternallybored.org/misc/gifsicle/) for your OS.
The library is currently pretty plain: it offers a wrapper to gifsicle and a method to optimize gifs, wrapping the options for gifsicle.
To optimize a gif, use the following:
from pygifsicle import optimize
optimize("path_to_my_gif.gif")
To run gifsicle from Python use the following:
from pygifsicle import gifsicle
gifsicle(
sources=["list.gif", "of.gif", "gifs.gif"], # or a single_file.gif
destination="destination.gif" # or just omit it and will use the first source provided.
optimize=False, # Whetever to add the optimize flag of not
colors=256, # Number of colors t use
options=["--verbose"] # Options to use.
)