comparison 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
comparison
equal deleted inserted replaced
91:e17886c8da43 92:03b02463cc16
1 #!/usr/bin/env python
2
3 import sys, os
4 from PIL import Image
5
6
7 # return codes:
8 # 0 = ok
9 # 1 = error opening file (not an image, not a file, unreadable or whatever)
10 # 2 = error saving file (no write permission)
11 # 3 = not a png file
12 def repng(filename):
13 retcode = 0
14 try:
15 im = Image.open(filename)
16 if im.format == "PNG":
17 try:
18 im.save(filename, optimize=1)
19 except:
20 retcode = 3
21 else:
22 retcode = 2
23 except:
24 retcode = 1
25 return retcode
26
27 def hbytes(inbyte):
28 units = ["B", "kB", "MB", "GB", "TB", "PB"]
29 outbyte = float(inbyte)
30 current_unit = 0
31 while outbyte > 1000:
32 outbyte /= 1000
33 current_unit += 1
34 return "%.2f %s" % (outbyte, units[current_unit])
35
36 if __name__ == "__main__":
37 for filename in sys.argv[1:]:
38 print "Recompressing %s:" % filename,
39 sys.stdout.flush()
40 try:
41 byte_orig = os.path.getsize(filename)
42 re = repng(filename)
43 if re == 0:
44 byte_new = os.path.getsize(filename)
45 print "OK (%s => %s, %.2f%% saving)" % (hbytes(byte_orig), hbytes(byte_new), (byte_orig - byte_new)*100/float(byte_orig)),
46 elif re == 1:
47 print "Not an image or corrupt file",
48 elif re == 2:
49 print "No write permission",
50 elif re == 3:
51 print "Not a PNG file",
52 except:
53 print "(%s: %s)" % (sys.exc_type, sys.exc_value)
54 print "Not a file or no read permission",
55 re = 1
56 print "[%s]" % re
57