1 import struct
, zlib
, sys
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
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
)
31 def read(fmt
): return struct
.unpack("!"+fmt
, f
.read(struct
.calcsize("!"+fmt
)))
32 def skip(count
): f
.read(count
)
35 if read("cccccccc") != ('\x89', 'P', 'N', 'G', '\r', '\n', '\x1a', '\n'):
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
52 imagedata
+= f
.read(size
)
55 break # we are done! \o/
57 skip(size
+4) # skip unknown chunks
59 # decompress image data
60 rawdata
= map(ord, zlib
.decompress(imagedata
))
62 # apply per scanline filters
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
)]
76 if pa
<= pb
and pa
<= pc
:
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]
92 imgdata
+= thisline
[4:]
96 raw
+= struct
.pack("B", x
)
98 #print len(raw), width*height*4
99 write_tga(file("test2.tga", "w"), width
, height
, 32, raw
)
102 load_png(file("butterfly2.png", "rb"))