]>
git.saurik.com Git - wxWidgets.git/blob - misc/scripts/png2c.py
3 # This script is a slightly modified version of the original found at
5 # http://wiki.wxwidgets.org/Embedding_PNG_Images-Bin2c_In_Python
7 # without any copyright attribution so it is assumed it can be used under
8 # wxWindows licence as the rest of the wiki material.
16 USAGE
= """Usage: png2c [-s] [file...]
17 Output input PNG files as C arrays to standard output. Used to embed PNG images
18 in C code (like XPM but with full alpha channel support).
20 -s embed the image size in the image names in generated code."""
26 r
= re
.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][pP][nN][gG]$")
30 for path
in sys
.argv
[1:]:
35 filename
= os
.path
.basename(path
).replace('-','_')
38 # Allow only filenames that make sense as C variable names
40 print "Skipped file (unsuitable filename): " + filename
43 # Read PNG file as character array
44 bytes = array
.array('B', open(path
, "rb").read())
47 # Check that it's actually a PNG to avoid problems when loading it
50 # Each PNG file starts with a 8 byte signature that should be followed
51 # by IHDR chunk which is always 13 bytes in length so the first 16
52 # bytes are fixed (or at least we expect them to be).
53 if bytes[0:16].tostring() != '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR':
54 print '"%s" doesn\'t seem to be a valid PNG file.' % filename
57 # Try to naively get its size if necessary
59 width
= bytes[19] + 16*bytes[18] + 256*bytes[17] + 4096*bytes[16]
60 height
= bytes[23] + 16*bytes[22] + 256*bytes[21] + 4096*bytes[20]
61 size_suffix
= "_%dx%d" % (width
, height
)
64 text
= "/* %s - %d bytes */\n" \
65 "static const unsigned char %s%s_png[] = {\n" % (
66 filename
, count
, m
.group(1), size_suffix
)
68 # Iterate the characters, we want
70 # 0x01, 0x02, .... (8 values per line maximum)
74 # Every new line starts with two whitespaces
77 # Then the hex data (up to 8 values per line)
78 text
+= "0x%02x" % (byte
)
79 # Separate all but the last values
86 # Now conclude the C source