使用TinyPNG批量压缩图片脚本

在Android打包过程中,aapt工具会自动对那些没进行过无损压缩的png图片做无损压缩优化,但是如果你发现项目中用到png、jpg格式的图片还是有些太大、严重影响apk安装包的大小时,可以用TinyPNG工具对项目中用到的图片进行一次压缩。虽然TinyPNG压缩是有损的,但是由于算法很屌,对大多数图片可以减小30%-70%的体积,并且清晰度肉眼基本看不出来变化!这点实在是太诱人了。另外,TinyPNG不止可以压缩png格式,jpg、9图同样可以压缩。但是缺点是在压缩某些带有过渡效果(带alpha值)的图片时,图片会失真,这种情况可以把图片转换位webP格式。

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode
import json
import sys,os
import time
# created by qianzui at 2014/05/25
key = "" // key替换成自己申请的
src_dir = ""
dest_dir = ""
record = {}
def tinypng (src_dir,dest_dir) :
if os.path.isdir(src_dir) :
for curfile in os.listdir(src_dir) :
#print "current src dir : " + src_dir
#print "current dest dir : " + dest_dir
full_path = os.path.join(src_dir,curfile)
if os.path.isdir(full_path):
tinypng(full_path, os.path.join(dest_dir,curfile))
elif curfile.lower().find(".png") != -1 or curfile.lower().find(".jpg") != -1:
print "current tiny image : " + full_path
if not os.path.isdir(dest_dir) :
os.makedirs(dest_dir)
request = Request("https://api.tinypng.com/shrink", open(full_path, "rb").read())
# add the auth
auth = b64encode(bytes("api:" + key)).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
# http post request
response = urlopen(request)
result_json = json.loads(response.read().strip())
print "response json : " + str(result_json)
if response.getcode() == 201 :
# Compression was successful, retrieve output from Location header.
download_url = response.info().getheader("Location")
print "tinypng download url : " + download_url
result = urlopen(download_url).read()
output_path = os.path.join(dest_dir,curfile)
open(output_path, "wb").write(result)
record[full_path] = download_url
print("Success! Compression ratio : " + str(result_json["output"]["ratio"]))
else :
# Something went wrong! You can parse the JSON body for details.
print("error : " + result_json["error"] + "\n message : " + result_json["message"])
def write_record (record_file) :
#write result
output = open(record_file,'w')
for k,v in record.iteritems() :
line = "%s\t%s\n" % (k,v)
line = line.encode('utf-8')
output.write(line)
print "write record completed!"
output.close()
if __name__ == "__main__" :
if len(sys.argv) == 3 :
src_dir = sys.argv[1]
dest_dir = sys.argv[2]
tinypng(src_dir,dest_dir)
record_file = os.path.join(dest_dir,time.strftime("%Y%m%d-%H%M%S") + ".txt")
write_record(record_file)
else :
print "Usage : python image_dir result_dir"

上面是自己写的一个python脚本,逻辑比较简单,就是按照TinyPNG的API规范发送请求,拿到响应结果后读取压缩后图片的url,进行图片下载、保存即可。

支持把指定目录下的图片文件进行TinyPNG批量压缩到指定目录。key自己到tinypng网站上自己申请一个,虽然一个月的请求次数有限制,但对于个人用户来说足够了。

执行: python tinypng.py ~/imagefloder ~/tinypngfloder