1. 程式人生 > 其它 >Python-壓縮gif圖片大小

Python-壓縮gif圖片大小

使用PIL、imageio,將gif拆幀、壓縮、合成。博主使用的是PyCharm工具。

1、安裝imageio。File-->Settings-->Project: pro-->Project Interpreter-->點選 右上角的“+”搜尋“imageio”安裝。

2、提取gif每一幀並儲存jpg格式,這裡使用.convert('RGB')是因為frame.save不能儲存png格式的圖片,下同。

def getFrames(im):
    #非動畫
    if False == im.is_animated :
        return
    index = 1
    for frame in ImageSequence.Iterator(im):
        frame = frame.convert('RGB')
        frame.save("g%d.jpg" % index)
        compressImg('g%d.jpg'% index)
        index = index + 1
    return index

3、壓縮圖片。

def compressImg(ImgName):
    im = Image.open(ImgName)
    im.convert('RGB')
    if max(im.size[0], im.size[1]) > 780:
        im.thumbnail((780, 780))
    im.save('f-'+ImgName, quality=50)
    return 'OK'

4、將之前拆開的jpg檔案合成gif。

def compressGif(ind,dur):
    images = []
    for i in range(1, ind):
        images.append(imageio.imread('f-g%d.jpg' % i))
    imageio.mimsave('c001.gif', images, duration = dur)

5、計算幀之間的頻率,獲取到的是毫秒,duration是秒,所以除以1000。

def calDuration(im):
    return (im.info)['duration']/1000

6、移除圖片。

def removeImg(ind):
    for i in range(1,ind):
        af = 'f-g' + str(i) + '.jpg'
        f = 'g' + str(i) + '.jpg'
        if os.path.exists(af):
            os.remove(af)
        if os.path.exists(f):
            os.remove(f)

呼叫函式的程式碼(主函式)

gif = Image.open("gav27.gif")   #讀取檔案
cnt = getFrames(gif)    #提取每一幀,儲存為jpg格式,返回總幀數,此過程會生成許多jpg檔案
duration = calDuration(gif) #計算幀之間的頻率,間隔毫秒
compressGif(cnt, duration)  # 壓縮jpg,合併jpg成gif
removeImg(cnt)  # 刪除中間jpg檔案

總體程式碼如下:

import imageio
import os
from PIL import Image, ImageSequence
import moviepy.editor as mpy

def getFrames(im):
    #非動畫
    if False == im.is_animated :
        return
    index = 1
    for frame in ImageSequence.Iterator(im):
        frame = frame.convert('RGB')
        frame.save("g%d.jpg" % index)
        compressImg('g%d.jpg'% index)
        index = index + 1
    return index

def compressImg(ImgName):
    im = Image.open(ImgName)
    im.convert('RGB')
    if max(im.size[0], im.size[1]) > 780:
        im.thumbnail((780, 780))
    im.save('f-'+ImgName, quality=50)
    return 'OK'

def compressGif(ind,dur):
    images = []
    for i in range(1, ind):
        images.append(imageio.imread('f-g%d.jpg' % i))
    imageio.mimsave('c001.gif', images, duration = dur)

def calDuration(im):
    return (im.info)['duration']/1000

def removeImg(ind):
    for i in range(1,ind):
        af = 'f-g' + str(i) + '.jpg'
        f = 'g' + str(i) + '.jpg'
        if os.path.exists(af):
            os.remove(af)
        if os.path.exists(f):
            os.remove(f)


gif = Image.open("gav27.gif")   #讀取檔案
cnt = getFrames(gif)    #提取每一幀,儲存為jpg格式,返回總幀數,此過程會生成許多jpg檔案
duration = calDuration(gif) #計算幀之間的頻率,間隔毫秒
compressGif(cnt, duration)  # 壓縮jpg,合併jpg成gif
removeImg(cnt)  # 刪除中間jpg檔案

效果如下所示: