当前位置: 首页 > 工具软件 > TinyPNG4Mac > 使用案例 >

使用TinyPNG批量压缩图片

轩辕欣可
2023-12-01

注册apikey

https://tinypng.com/developers

安装环境

需要用到python,pip

1、安装python

Python 2 需要大于2.7.9

 brew install python

或者 Python 3: 需要大于等于3.4

brew install python3

2、安装pip
使用pip官网get-pip.py安装一直不成功,通过下面命令可以

sudo easy_install pip 

3、安装tinify

sudo pip install --upgrade tinify

编写python脚本 tinypng.py

import tinify
import os
import os.path
import sys
print "name:", sys.argv[0]
tinify.key ="xxxxx" # AppKey
if len(sys.argv) < 3:
    print "params length is error"
    sys.exit()
else:
    fromPath = sys.argv[1] # source path
    toPath = sys.argv[2] # dest path
for root, dirs, files in os.walk(fromPath):
    newToPath = toPath
    if len(root) > len(fromPath):
        innerPath= root[len(fromPath):]
        if innerPath[0] == '/':
            innerPath = innerPath[1:]
        newToPath =  os.path.join(toPath,innerPath)
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':
        source = tinify.from_file(newFromFilePath)
        source.to_file(newToFilePath)
        print "compression successful : ", name
    else:
        pass
for dirName in dirs:
    os.mkdir(os.path.join(newToPath, dirName))

使用

python tinypng.py  frompath  topath
 类似资料: