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