Created
June 19, 2015 22:42
Batch compress PNG images by using TinyPNG
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
""" | |
Batch compress PNG images by using TinyPNG | |
usage: | |
tinyPNG.py <key> <target-folder> <source-file>... | |
""" | |
import os | |
import glob | |
import sys | |
import re | |
import shutil | |
from urllib.request import Request, urlopen | |
from base64 import b64encode | |
from docopt import docopt | |
if __name__ == '__main__': | |
args = docopt(__doc__) | |
key = args['<key>'] | |
files = args['<source-file>'] | |
target = os.path.abspath(args['<target-folder>']) | |
for idx, source in enumerate(files): | |
name = os.path.basename(source) | |
expr = re.compile(r'.+\.png') | |
match = expr.match(name) | |
if match is None: | |
print("%d/%d Skipped %s" % (idx + 1, len(files), source)) | |
continue | |
request = Request("https://api.tinify.com/shrink", open(source, "rb").read()) | |
auth = b64encode(bytes("api:" + key, "ascii")).decode("ascii") | |
request.add_header("Authorization", "Basic %s" % auth) | |
response = urlopen(request) | |
if response.status == 201: | |
# Compression was successful, retrieve output from Location header. | |
result = urlopen(response.getheader("Location")).read() | |
open(target + "/" + name, "wb").write(result) | |
print("%d/%d Compressed %s" % (idx + 1, len(files), source)) | |
else: | |
# Something went wrong! You can parse the JSON body for details. | |
print("%d/%d failed %s" % (idx + 1, len(files), source)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment