There seem to be two ways to do this. I can either do what Simon N. suggested, or I can convert the images to a C-array and compile them into source code. I decided to do the latter, as I can do it easily on the home side. I even created python (v3.2) to convert the png file to the header of the c array and the source file. This requires PyPNG
import png
import re
import itertools
def grouper(n, iterable, fillvalue=None):
args = [iter(iterable)] * n
return itertools.zip_longest(fillvalue=fillvalue, *args)
def expand(array):
new_array = [];
for row in array:
for v in row:
new_array.append(v)
return new_array
def c_array_name(filename):
'''converts the filename to the c array name'''
return re.sub(r'\W', '_', filename)
def c_array_header_filename(filename):
'''converts the filename to the c array header filename'''
return "{0}.h".format(filename)
def c_array_source_filename(filename):
'''converts the filename to the c array source filename'''
return "{0}.cpp".format(filename)
def c_array_header(filename):
'''returns a string that is the c array header,
where
filename is the png file'''
name = c_array_name(filename)
return """
#ifndef __{0}__
#define __{0}__
#include <stdint.h>
extern uint_least32_t const {1}[];
#endif /* __{0}__ */
""".format(name.upper(), name)
def c_array_source(filename, header_filename, array_string):
'''returns a string that is the c array source,
where
name is the value from c_array_name
array_string'''
name = c_array_name(filename)
return """
#include "{0}"
uint_least32_t const {1}[] = {{
{2}
}};
""".format(header_filename, name, array_string)
def convert_data_array_string(data):
'''returns a string of hexes of bytes,
where
data is a map of bytes'''
return ", ".join(["0x{:02x}{:02x}{:02x}{:02x}".format(a, b, g, r)
for r, g, b, a in grouper(4, expand(data), 0)])
def png_data_from_file(path):
'''returns a map of bytes of the png file'''
with open(path, 'rb') as file:
reader = png.Reader(file = file)
data = reader.read();
return list(data[2]);
if __name__ == '__main__':
import sys
import os
if len(sys.argv) != 2:
sys.stdout.write("{0} image_path".format(sys.argv[0]))
exit()
path = sys.argv[1]
filename = os.path.split(path)[1]
header_filename = c_array_header_filename(filename)
sys.stdout.write("Creating header file '{}'... ".format(header_filename))
with open(header_filename, 'w') as header_file:
header_file.write(c_array_header(filename))
sys.stdout.write("done\n")
source_filename = c_array_source_filename(filename)
sys.stdout.write("Creating source file '{}'... ".format(source_filename))
data = png_data_from_file(path)
with open(source_filename, 'w') as source_file:
source_file.write(c_array_source(filename, header_filename, convert_data_array_string(data)))
del data
sys.stdout.write("done\n")
source
share