Skip to content

Instantly share code, notes, and snippets.

@crsnbrt
Last active August 29, 2015 14:09
Show Gist options
  • Save crsnbrt/8d74057d451e9e398cd5 to your computer and use it in GitHub Desktop.
Save crsnbrt/8d74057d451e9e398cd5 to your computer and use it in GitHub Desktop.
Loop recursively through a directory and compress all image files using the TinyPng Api https://tinypng.com/developers
import os
from os.path import dirname
from urllib2 import Request, urlopen
from base64 import b64encode
compress_png = True
compress_jpg = True
import_dir = '<INPUT DIR>'
output_dir = "<OUTPUT DIR>"
tiny_png_key = '<API KEY>'
tiny_png_url = 'https://api.tinypng.com/shrink'
img_count = 0
file_count = 0
compress_count = 0
existing_count = 0
def compressImage(filepath, filedest, overwrite = False):
global compress_count
global existing_count
if not os.path.isfile(filedest) or overwrite:
status = ''
request = Request(tiny_png_url, open(filepath, "rb").read())
auth = b64encode(bytes("api:" + tiny_png_key)).decode("ascii")
request.add_header("Authorization", "Basic %s" % auth)
response = urlopen(request)
if response.getcode() == 201:
status = "success";
headers = response.info()
result = urlopen(headers["Location"]).read()
if not os.path.exists(os.path.dirname(filedest)):
os.makedirs(os.path.dirname(filedest))
open(filedest, "wb").write(result)
compress_count += 1
else:
status = "failed"
print 'Compressing: %s\nFile: %s\nStatus: %s\n'%(filepath, img_count, status)
else:
existing_count += 1
# loop througs files in import_dir recursively
for subdir, dirs, files in os.walk(import_dir):
for file in files:
filepath = os.path.join(subdir, file)
fileName, fileExtension = os.path.splitext(file)
file_count += 1
if(fileExtension == '.png' and compress_png) or (fileExtension == '.jpg' and compress_jpg):
img_count += 1
filedest = filepath.replace(import_dir, output_dir)
compressImage(filepath, filedest)
print '================'
print 'Total Files: %s'%(file_count)
print 'Total Images: %s'%(img_count)
print 'Images Compressed: %s'%(compress_count)
print 'Images Previously Compressed (Exist in output directory): %s'%(existing_count)
@crsnbrt
Copy link
Author

crsnbrt commented Nov 17, 2014

Other Notes

  • Compatible with Python 2.7
  • Duplicates the directory structure and filenames of input_dir in the output_dir
  • By default the request is not made if the corresponding file already exists in the output directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment