added for Slovak translation by LimiT
[twcon.git] / scripts / png.py
blob739b1a7a1ad33ce56281dd4238b27bf075ca7b70
1 import struct, zlib, sys
3 class image:
4 w = 0
5 h = 0
6 data = []
8 def read_tga(f):
9 image = f.read()
10 img_type = struct.unpack("<B", image[2:3])[0]
11 img_bpp = struct.unpack("<B", image[16:17])[0]
12 img_width = struct.unpack("<H", image[12:14])[0]
13 img_height = struct.unpack("<H", image[14:16])[0]
15 if img_type != 2 or img_bpp != 32:
16 print "image must be a RGBA"
18 start = 18+struct.unpack("B", image[0])[0]
19 end = start + img_width*img_height*4
20 image_data = image[start:end] # fetch raw data
21 return image_data
23 def write_tga(f, w, h, bpp, data):
24 f.write(struct.pack("<BBBHHBHHHHBB", 0, 0, 2, 0, 0, 0, 0, 0, w, h, bpp, 0) + data)
30 def load_png(f):
31 def read(fmt): return struct.unpack("!"+fmt, f.read(struct.calcsize("!"+fmt)))
32 def skip(count): f.read(count)
34 # read signature
35 if read("cccccccc") != ('\x89', 'P', 'N', 'G', '\r', '\n', '\x1a', '\n'):
36 return 0
38 # read chunks
39 width = -1
40 height = -1
41 imagedata = ""
42 while 1:
43 size, id = read("I4s")
44 if id == "IHDR": # read header
45 width, height, bpp, colortype, compression, filter, interlace = read("IIBBBBB")
46 if bpp != 8 or compression != 0 or filter != 0 or interlace != 0 or (colortype != 2 and colortype != 6):
47 print "can't handle png of this type"
48 print width, height, bpp, colortype, compression, filter, interlace
49 return 0
50 skip(4)
51 elif id == "IDAT":
52 imagedata += f.read(size)
53 skip(4) # read data
54 elif id == "IEND":
55 break # we are done! \o/
56 else:
57 skip(size+4) # skip unknown chunks
59 # decompress image data
60 rawdata = map(ord, zlib.decompress(imagedata))
62 # apply per scanline filters
63 pitch = width*4+1
64 bpp = 4
65 imgdata = []
66 prevline = [0 for x in xrange(0, (width+1)*bpp)]
67 for y in xrange(0,height):
68 filter = rawdata[pitch*y]
69 pixeldata = rawdata[pitch*y+1:pitch*y+pitch]
70 thisline = [0 for x in xrange(0,bpp)]
71 def paeth(a, b, c):
72 p = a + b - c
73 pa = abs(p - a)
74 pb = abs(p - b)
75 pc = abs(p - c)
76 if pa <= pb and pa <= pc:
77 return a
78 if pb <= pc:
79 return b
80 return c
82 if filter == 0: f = lambda a,b,c: 0
83 elif filter == 1: f = lambda a,b,c: a
84 elif filter == 2: f = lambda a,b,c: b
85 elif filter == 3: f = lambda a,b,c: (a+b)/2
86 elif filter == 4: f = paeth
88 for x in xrange(0, width*bpp):
89 thisline += [(pixeldata[x] + f(thisline[x], prevline[x+bpp], prevline[x])) % 256]
91 prevline = thisline
92 imgdata += thisline[4:]
94 raw = ""
95 for x in imgdata:
96 raw += struct.pack("B", x)
98 #print len(raw), width*height*4
99 write_tga(file("test2.tga", "w"), width, height, 32, raw)
100 return 0
102 load_png(file("butterfly2.png", "rb"))