Mercurial > ec-dotfiles
view bin/recompress @ 657:91d7c2e5936c
Remove need to manually switch directory with sud
author | nanaya <me@nanaya.pro> |
---|---|
date | Sun, 25 Jul 2021 21:36:52 +0900 |
parents | 97e24e89388f |
children |
line wrap: on
line source
#!/usr/bin/env python import sys, os from PIL import Image # Raises a generic exception (exception.Exception) if input is not a PNG file. def repng(filename): im = Image.open(filename) if im.format == "PNG": im.save(filename, "PNG", optimize=1) else: raise Exception("Not a PNG image file") 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]) def sane_fn(filename): import re return re.sub(r"[\x00-\x1F\x7F\n\r]", "?", filename) def main(files): for filename in files: print "Recompressing %s:" % sane_fn(filename), sys.stdout.flush() try: byte_orig = os.path.getsize(filename) repng(filename) 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)), re = 0 except: print "Failed", print "(%s: %s)" % (sys.exc_type, sys.exc_value), re = 1 finally: print "[%s]" % re if __name__ == "__main__": main(sys.argv[1:])