tinypng,批量压缩脚本

该脚本用 Python 编写,应用到了tinify模块,Mac 自带 Python 环境,但是没有 tinify 模块,也没有Python包管理工具,需要先安装 pip 包管理工具,然后再通过 pip 安装 tinify,

在官网下载 pip 然后解压,https://pypi.python.org/pypi/pip ,第二个


在终端 cd 到解压后目录 ,然后执行

sudo python setup.py install
安装成功后看一下版本号

pip -v

然后安装 tinify 模块

sudo pip install --upgrade tinify

然后获取 API key
https://tinypng.com/developers 到他们网站申请,只需要一个名字和一个邮箱就可以,API key会以链接的形式发到邮箱里

然后在终端执行 Python 脚本代码就 ok  

python tinypng.py /Users/wolf/Resource/Assets.xcassets


#coding:utf-8
#/usr/bin/python

import os
import sys
import os.path
import shutil
import tinify

temPath = os.getcwd()+'/'+'temDir'			# 临时目录,注意该脚本最后是要删掉这个临时目录的
tinify.key = "U54uo4N330OaU_85vEgHv63djEf2ej"		# 刚刚申请的API KEY
version = "0.0.1"				# 版本

# 压缩的核心
def compress_core(inputFile, outputFile, img_width):
	source = tinify.from_file(inputFile)
	if img_width is not -1:
		resized = source.resize(method = "scale", width  = img_width)
		resized.to_file(outputFile)
	else:
		source.to_file(outputFile)

# 压缩一个文件夹下的图片
def compress_path(path, width):
    print "compress_path-------------------------------------"
    fromFilePath = path 			# 源路径
    print "fromFilePath=%s" %fromFilePath

    for root, dirs, files in os.walk(fromFilePath):
        print "root = %s" %root
        print "dirs = %s" %dirs
        print "files= %s" %files
        for name in files:
            fileName, fileSuffix = os.path.splitext(name)
            if fileSuffix == '.png' or fileSuffix == '.jpg' or fileSuffix == '.jpeg':
                fromfile =  os.path.join(root,name)
                tofile = os.path.join(temPath,name)
                print fromfile
                print  tofile
                compress_core(fromfile, tofile, width)
                shutil.copy2(tofile, fromfile)# 将压缩后的文件覆盖原文件



if __name__ == "__main__":
    if not os.path.exists(temPath):
        os.mkdir(temPath)
    if len(sys.argv)==2:
        compress_path(sys.argv[1],-1)
    if len(sys.argv)==3:
        compress_path(sys.argv[1],sys.argv[2])
    shutil.rmtree(temPath)

tinypng 免费版一个月最多能压缩500张,可以在下面网址查看
https://tinypng.com/dashboard/developers


参考文章:

[Python模块学习]用tinify模块压缩和优化图片





猜你喜欢

转载自blog.csdn.net/langzxz/article/details/77895178