tinypng的python批量壓縮圖片功能


tinypng網站提供的圖片壓縮功能很不錯,但是直接在網站上壓縮有限制,大量壓縮圖片時比較麻煩,還好官方提供了很多腳本的自動化壓縮接口。下面簡單說下python批量壓縮步驟。

1.申請api key

https://tinypng.com/developers申請自己的key,每個key每個月500次

2.使用pip進行安裝:pip install --upgrade tinify

3.導入tinify模塊,設置key

import tinify
tinify.key = "API_KEY" # 此處填入你自己申請的API key

4.上傳文件: 
文件上傳的形式共有三種:本地文件、二進制、URL。 
上傳文件后,服務器會自動識別文件類型,根據類型自動調用TinyPNG或TinyJPG的壓縮引擎。調用to_file函數就可以將壓縮優化過后的圖片保存至本地。

示例代碼:

def ShrinkStudioDisperseRes(_destDirName):
    #log
    print("---call ShrinkStudioDisperseRes")

    global G_TinifyKey

    curCwd=os.getcwd()
    #srcRootDirStr = "%s/../../studioPrj/sanGuoPrjDev/cocosstudio/res/com" % (curCwd)
    srcRootDirStr = "%s/../../SanGuoDev/Resources/studioRes/plist" % (curCwd)
    destRootDirStr = "%s/%s/exptImg/allplist" % (curCwd,_destDirName)
    fileCount=0
    tinify.key =G_TinifyKey[4]

    #創建輸出目錄
    if(os.path.isdir(destRootDirStr)):
        shutil.rmtree(destRootDirStr)
    os.makedirs(destRootDirStr)

    for root, dirs, files in os.walk(srcRootDirStr):
        curCount=len(files)
        if(curCount>0):
            print("---compressDir=%s fileCount=%s" %(root,fileCount))

        #目的目錄
        newToPath = destRootDirStr
        if len(root) > len(srcRootDirStr):
            innerPath= root[len(srcRootDirStr):]
            if innerPath[0] == '\\': 
                innerPath = innerPath[1:]
            newToPath = os.path.join(destRootDirStr,innerPath)
            #print("---newToPath=%s" %(newToPath))

        #創建目的目錄
        for dirName in dirs:
            if os.path.exists(os.path.join(newToPath, dirName)):
                pass
            else:
                os.mkdir(os.path.join(newToPath, dirName))

        #遍歷壓縮文件
        for name in files:
            newFromFilePath = os.path.join(root, name)
            newToFilePath = os.path.join(newToPath, name)
            fileName,fileSuffix = os.path.splitext(name)
            if fileSuffix == '.png' or fileSuffix == '.jpg':
                fileCount=fileCount+1
                print("---compressing newFromFilePath=%s" %(newFromFilePath))
                source = tinify.from_file(newFromFilePath)
                source.to_file(newToFilePath)
            
    print("----------compress ok! fileCount=%s"%(fileCount))

  可以通過tinify.compression_count查看當月的API調用次數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM