1. 程式人生 > >使用TinyPNG批量壓縮圖片

使用TinyPNG批量壓縮圖片

註冊apikey

安裝環境

需要用到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