Mercurial > ec-dotfiles
view bin/recompress @ 93:4f954c1e2fdc
Stop being pretentious and only return 0 or 1 in case of success or failure. Everything else is handled by exception handler.
author | Edho Prima Arief <edho@myconan.net> |
---|---|
date | Thu, 14 Jul 2011 00:39:09 +0700 |
parents | 03b02463cc16 |
children | 9790bc126ea6 |
line wrap: on
line source
#!/usr/bin/env python import sys, os from PIL import Image # return codes: # 0 = ok # 1 = error opening file (not an image, not a file, unreadable or whatever) # 2 = error saving file (no write permission) # 3 = not a png file def repng(filename): retcode = 0 im = Image.open(filename) if im.format == "PNG": im.save(filename, optimize=1) else: retcode = 1 return retcode def hbytes(inbyte): units = ["B", "kB", "MB", "GB", "TB", "PB"] outbyte = float(inbyte) current_unit = 0 while outbyte > 1000: outbyte /= 1000 current_unit += 1 return "%.2f %s" % (outbyte, units[current_unit]) if __name__ == "__main__": for filename in sys.argv[1:]: print "Recompressing %s:" % filename, sys.stdout.flush() try: byte_orig = os.path.getsize(filename) re = repng(filename) if re == 0: byte_new = os.path.getsize(filename) print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)), elif re == 1: print "Not a PNG image file", except: print "Failed", print "(%s: %s)" % (sys.exc_type, sys.exc_value), re = 1 print "[%s]" % re