1#!/usr/bin/python
2"""
3Converts all .png files into this directory to a .h & one .cpp
4file.
5"""
6import sys
7import os
8import os.path
9import re
10import array
11import glob
12
13r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][pP][nN][gG]$")
14
15header_file = open("pngfiles.h", "wb")
16source_file = open("pngfiles.cpp", "wb")
17
18header_file.write("#ifndef __PNG_HEADER_FILE_H__\n")
19header_file.write("#define __PNG_HEADER_FILE_H__\n")
20
21png_files = glob.glob("*.png")
22
23for path in png_files:
24 filename = os.path.basename(path)
25 m = r.match(filename)
26 # Allow only filenames that make sense
27 # as C variable names
28 if not(m):
29 print "Skipped file (unsuitable filename): " + filename
30 continue
31
32 # Read PNG file as character array
33 bytes = array.array('B', open(path, "rb").read())
34 count = len(bytes)
35
36 # Output to header
37 header_file.write("extern unsigned char " + m.group(1) + "_png[" + str(count) + "];\n")
38 # Create the C file
39 text = "/* " + filename + " - " + str(count) + " bytes */\nunsigned char " + m.group(1) + "_png[" + str(count) + "] = {\n"
40
41 # Iterate the characters, we want
42 # lines like:
43 # 0x01, 0x02, .... (8 values per line maximum)
44 i = 0
45 count = len(bytes)
46 for byte in bytes:
47 # Every new line starts with two whitespaces
48 if (i % 8) == 0:
49 text += " "
50 # Then the hex data (up to 8 values per line)
51 text += "0x%02x" % (byte)
52 # Separate all but the last values
53 if (i + 1) < count:
54 text += ", "
55 if (i % 8) == 7:
56 text += '\n'
57 i += 1
58
59 # Now conclude the C source
60 text += "};\n/* End Of File */\n"
61
62 source_file.write(text)
63
64header_file.write("#endif //__PNG_HEADER_FILE_H__\n")
65
66