File: png2c.py

package info (click to toggle)
springlobby 0.255%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 14,228 kB
  • ctags: 14,450
  • sloc: cpp: 76,178; ansic: 61,718; python: 863; sh: 654; perl: 238; xml: 52; makefile: 41; sed: 16
file content (57 lines) | stat: -rwxr-xr-x 1,407 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
import sys
import os
import os.path
import re
import array

## no need to call this manually, use make_header_from_png.sh instead
## 

USAGE = """png2c - Embed a PNG in a C header file (like XPM)
Usage: png2c [file ..] Convert all the file <file.png> to <file.png.h>"""
 
if len(sys.argv) < 2:
	print USAGE
	sys.exit(1)
 
r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][pP][nN][gG]$")
 
for path in sys.argv[1:]:
	filename = os.path.basename(path)
	m = r.match(filename)
	# Allow only filenames that make sense
	# as C variable names
	if not(m):
		print "Skipped file (unsuitable filename): " + filename
		continue
 
	# Read PNG file as character array
	bytes = array.array('B', open(path, "rb").read())
	count = len(bytes)
 
	# Create the C header
	text = "/* %s - %d bytes */\n static const unsigned char %s_png[] = {\n" % (filename, count, m.group(1))
 
	# Iterate the characters, we want
	# lines like:
	#   0x01, 0x02, .... (8 values per line maximum)
	i = 0
	count = len(bytes)
	for byte in bytes:
		# Every new line starts with two whitespaces
		if (i % 8) == 0:
			text += "  "
		# Then the hex data (up to 8 values per line)
		text += "0x%02x" % (byte)
		# Separate all but the last values 
		if (i + 1) < count:
			text += ", "
		if (i % 8) == 7:
			text += '\n'
		i += 1
 
	# Now conclude the C source
	text += "};\n/* End Of File */\n"
 
	open(path + ".h", 'w').write(text)