python结合tinypng批量压缩图片

目的

在使用TinyPNG压缩图片的时候偶尔会遇到需要压缩很多张,网站使用起来需要本地选择图片然后上传再下载压缩之后的图片,很不方便,所以想搞一个脚本在本地运行可以递归压缩文件夹及子文件夹中的所有图片。

准备工作

查阅资料后发现python有一个可以很契合这个需求的库,所以直接使用python吧~

首先安装一下tinify:

1
pip install --upgrade tinify

然后去TinyPNG申请一个key,一个key每个月可以免费压缩500张

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import tinify
import os
import os.path

tinify.key ="XXXXXXXX"
fromPath ="/Users/realzzz/Desktop/temp-test/pic-test/source" # source path
toPath ="/Users/realzzz/Desktop/temp-test/pic-test/dest" # 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)
else:
pass

for dirName in dirs:
os.mkdir(os.path.join(newToPath, dirName))

完事了