Skip to content

Instantly share code, notes, and snippets.

@chibatching
Created June 19, 2015 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chibatching/96e596c2c5f1dca91ac7 to your computer and use it in GitHub Desktop.
Save chibatching/96e596c2c5f1dca91ac7 to your computer and use it in GitHub Desktop.
Batch compress PNG images by using TinyPNG
"""
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