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

最新文章

  1. 【转载】Java集合类Array、List、Map区别和联系
  2. 阿里聚安全受邀参加SFDC安全大会,分享互联网业务面临问题和安全创新实践
  3. NPM使用前设置和升级
  4. 还记得高中的向量吗?leetcode 335. Self Crossing(判断线段相交)
  5. android 浏览器开发实例
  6. const和readonly差别
  7. 使用js判断一个对象是否为空 比如 obj={}
  8. 《炉石传说》建筑设计欣赏(6):卡&在执行数据时,组织能力
  9. 【Android】 分享一个完整的项目,适合新手!
  10. 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作
  11. UVA - 10118 Free Candies 记忆化搜索经典
  12. fetch()函数使用的一些技巧
  13. CnPack IDE 专家包(CnWizards)显示代引用单元列表
  14. tensorflow (七) k-means
  15. leetcode 846.Hand of Straights
  16. Python类继承,方法重写及私有方法
  17. leetcode1007
  18. Android分区
  19. CentOS 7开机不执行/etc/rc.local的解决方法
  20. Hadoop基础-Hadoop快照管理

热门文章

  1. C# 利用反射拷贝类
  2. hibernate 组件映射
  3. iOS开发一个制作Live Photo的工具
  4. Ffmpeg 视频教程 向视频中添加文字
  5. Android Shell Cmd
  6. Android---Handler消息处理机制
  7. memcache stats命令详解
  8. Atitit .h5文件上传 v3
  9. Atitit 插件机制原理与设计微内核 c# java 的实现attilax总结
  10. [k8s]简单启动一个k8s集群