The article introduces a way to reduce the size of the gif file. The python script analysis gif file and generate many png files from multiple frames. Then it takes a few png files to combine a new smaller gif file. In addition, You can use OpenCV to convert the colorful png file to a simple grey png file. It also reduces the size of the gif.

#! /usr/local/bin/python3
# -*- coding: utf-8 -*-

from PIL import Image
import cv2
import os
import imageio

"""
def ConvertWebp( picPath ):
    outputPath = picPath.split(".")[0] + ".webp"
    image = Image.open( picPath )
    image.save( outputPath )
"""

def AnalysisGif( gifPath ):
    image = Image.open(gifPath)
    pngDir = gifPath[:-4]
    if os.path.exists( pngDir ):
        files = os.listdir( pngDir )
        for file in files:
            file = pngDir + "/" + file
            os.remove( file )
        os.rmdir( pngDir )

    os.mkdir( pngDir )
    try:
        while True:
            current = image.tell()
            pngPath = pngDir+'/'+str(current)+'.png'
            image.save( pngPath, quality = 100 )
            image.seek( current+1 )
    except EOFError:
        print( EOFError )
        pass

def Combine2Gif( folderPath, gifFilePath ):
    files = os.listdir( folderPath )
    pngFiles = []
    for i in range(0, len(files), 5):
        pngFiles.append( folderPath + "/" + ('%d.png' % i) )

    GenerateGif( 0.1, gifFilePath, pngFiles )

def GenerateGif(step, gifPath, filterPngs):
    images = []
    for filePath in filterPngs:
        images.append( imageio.imread(filePath) )
    imageio.mimsave( gifPath, images, duration = step )

if __name__ == "__main__":
    gifPath = "/Users/weiyang/Desktop/test.gif"
    AnalysisGif( gifPath )
    Combine2Gif( gifPath[:-4], gifPath[:-4]+"_result.gif" )
    print( "== finished ==" )

Output:

$ du -h *.gif
 13M    test.gif
7.0M    test_result.gif
Categories: Python

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x