from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode
import json
import sys,os
import time
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) :
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())
auth = b64encode(bytes("api:" + key)).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)
result_json = json.loads(response.read().strip())
print "response json : " + str(result_json)
if response.getcode() == 201 :
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 :
print("error : " + result_json["error"] + "\n message : " + result_json["message"])
def write_record (record_file) :
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"