Skip to content

Instantly share code, notes, and snippets.

@shnya
Created June 11, 2015 03:20
Show Gist options
  • Save shnya/41493a95ffe10741d5dd to your computer and use it in GitHub Desktop.
Save shnya/41493a95ffe10741d5dd to your computer and use it in GitHub Desktop.
tinypng.py
#!/usr/bin/python
import tempfile
import sys
import urllib2
import shutil
import json
import base64
def request(api_key, data):
request = urllib2.Request("https://api.tinify.com/shrink", data)
base64string = base64.encodestring('%s:%s' % ("api", api_key)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
rec = json.loads(urllib2.urlopen(request).read())
return urllib2.urlopen(rec['output']['url']).read()
api_key = sys.argv[1]
input_file = sys.argv[2]
with open(input_file, 'r') as read_fh:
data = read_fh.read()
with tempfile.NamedTemporaryFile(delete=False) as write_fh:
write_fh.write(request(api_key, data))
output_file = write_fh.name
shutil.move(output_file, input_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment