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调用次数。

转载于:https://www.cnblogs.com/gamesky/p/8581263.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值