]>
Commit | Line | Data |
---|---|---|
ec20a753 VZ |
1 | #!/usr/bin/python |
2 | ||
3 | # This script is a slightly modified version of the original found at | |
4 | # | |
5 | # http://wiki.wxwidgets.org/Embedding_PNG_Images-Bin2c_In_Python | |
6 | # | |
7 | # without any copyright attribution so it is assumed it can be used under | |
8 | # wxWindows licence as the rest of the wiki material. | |
9 | ||
10 | import sys | |
11 | import os | |
12 | import os.path | |
13 | import re | |
14 | import array | |
15 | ||
16 | USAGE = """png2c - Embed a PNG in a C header file (like XPM) | |
17 | Usage: png2c [file ..] Output input PNG files as C structures on stdout""" | |
18 | ||
19 | if len(sys.argv) < 2: | |
20 | print USAGE | |
21 | sys.exit(1) | |
22 | ||
23 | r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][pP][nN][gG]$") | |
24 | ||
25 | for path in sys.argv[1:]: | |
26 | filename = os.path.basename(path) | |
27 | m = r.match(filename) | |
28 | # Allow only filenames that make sense | |
29 | # as C variable names | |
30 | if not(m): | |
31 | print "Skipped file (unsuitable filename): " + filename | |
32 | continue | |
33 | ||
34 | # Read PNG file as character array | |
35 | bytes = array.array('B', open(path, "rb").read()) | |
36 | count = len(bytes) | |
37 | ||
38 | # Create the C header | |
39 | text = "/* %s - %d bytes */\n" \ | |
40 | "static const unsigned char %s_png[] = {\n" % (filename, count, m.group(1)) | |
41 | ||
42 | # Iterate the characters, we want | |
43 | # lines like: | |
44 | # 0x01, 0x02, .... (8 values per line maximum) | |
45 | i = 0 | |
46 | count = len(bytes) | |
47 | for byte in bytes: | |
48 | # Every new line starts with two whitespaces | |
49 | if (i % 8) == 0: | |
50 | text += " " | |
51 | # Then the hex data (up to 8 values per line) | |
52 | text += "0x%02x" % (byte) | |
53 | # Separate all but the last values | |
54 | if (i + 1) < count: | |
55 | text += ", " | |
56 | if (i % 8) == 7: | |
57 | text += '\n' | |
58 | i += 1 | |
59 | ||
60 | # Now conclude the C source | |
61 | text += "};\n\n" | |
62 | ||
63 | print text |