Created
April 8, 2016 19:15
-
-
Save outsky/dc8722c199e1b571ed3dce71eafb9ab1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
import fnmatch | |
import sys | |
import datetime | |
import tinify | |
if len(sys.argv) != 3: | |
print("Usage: %s key src" % sys.argv[0]) | |
exit() | |
key = sys.argv[1] | |
src = sys.argv[2] | |
taskTimeStart = datetime.datetime.now() | |
print("Start compress photoes.\n\tkey:%s\n\tsrc:%s" % (key, src)) | |
def compress(srcFile, destFile): | |
timeStart = datetime.datetime.now() | |
print("\n%s -> %s ..." % (srcFile, destFile)) | |
try: | |
source = tinify.from_file(srcFile) | |
source.to_file(destFile) | |
timeUsed = datetime.datetime.now()-timeStart | |
srcSize = os.path.getsize(srcFile) | |
destSize = os.path.getsize(destFile) | |
print("\tDone. Time %d.%ds, %dK->%dK(%d%%)" % (timeUsed.seconds, timeUsed.microseconds, srcSize/1000, destSize/1000, 100*(srcSize-destSize)/srcSize)) | |
except Exception, e: | |
print("\tFailed: %s" % e) | |
exit() | |
def allfiles(root, patterns="*"): | |
patterns = patterns.split(";") | |
for path, subdirs, files in os.walk(root): | |
files.sort() | |
for name in files: | |
for pattern in patterns: | |
if fnmatch.fnmatch(name, pattern): | |
yield os.path.join(path, name) | |
break | |
if __name__ == "__main__": | |
try: | |
tinify.key = key | |
tinify.validate() | |
except Exception, e: | |
print("\tFailed: %s" % e) | |
exit() | |
for path in allfiles(src, "*.png;*.jpg"): | |
r,ext = os.path.splitext(path) | |
compress(path, r+".c"+ext) | |
taskTimeUsed = datetime.datetime.now()-taskTimeStart | |
print("\nTask done. Time %d.%ds" % (taskTimeUsed.seconds, taskTimeUsed.microseconds)) | |
print("Compressed used this month %d/500" % tinify.compression_count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment