diff bin/recompress @ 92:03b02463cc16

omg python, recompresses image files. Because mplayer's png writer doesn't write compressed png.
author Edho Prima Arief <edho@myconan.net>
date Thu, 14 Jul 2011 00:34:46 +0700
parents
children 4f954c1e2fdc
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/bin/recompress	Thu Jul 14 00:34:46 2011 +0700
@@ -0,0 +1,57 @@
+#!/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
+  try:
+    im = Image.open(filename)
+    if im.format == "PNG":
+      try:
+        im.save(filename, optimize=1)
+      except:
+        retcode = 3
+    else:
+      retcode = 2
+  except:
+    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 an image or corrupt file",
+      elif re == 2:
+        print "No write permission",
+      elif re == 3:
+        print "Not a PNG file",
+    except:
+      print "(%s: %s)" % (sys.exc_type, sys.exc_value)
+      print "Not a file or no read permission",
+      re = 1
+    print "[%s]" % re
+