/+junk/bin2cc

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/%2Bjunk/bin2cc

« back to all changes in this revision

Viewing changes to bin2cc.py

  • Committer: Gustav Hartvigsson
  • Date: 2014-06-29 20:04:18 UTC
  • Revision ID: gustav.hartvigsson@gmail.com-20140629200418-k45q3yb93vr46y80
TheĀ initialĀ code

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python3
 
2
 
 
3
import sys
 
4
from io import StringIO
 
5
from io import BufferedReader
 
6
import zlib
 
7
 
 
8
##################
 
9
# bin2cc - embedding compressed data in C files.
 
10
 
11
# 1) Do what the fuck you want with this code.
 
12
 
13
##################
 
14
# Examlpe:
 
15
# Create the C file with the compressed data:
 
16
# $ python3 bin2cc.py ../xorg.png > test.c
 
17
 
18
# Add this to the end of the file:
 
19
 
20
#int main (int argc, char ** argv) {
 
21
#  
 
22
#  unsigned char * out_buff = malloc(_xorg_png_real_len);
 
23
#  
 
24
#  uLongf outlen;
 
25
#  
 
26
#  uncompress (out_buff, &outlen, _xorg_png, _xorg_png_len);
 
27
#  
 
28
#  FILE * f = fopen ("../xorg_2.png", "wb");
 
29
#  fwrite (out_buff, 1, _xorg_png_real_len, f);
 
30
#  fclose (f);
 
31
#  return 0;
 
32
#}
 
33
##################
 
34
 
 
35
def main ():
 
36
  try:
 
37
    file_name = sys.argv[1]
 
38
  except IndexError:
 
39
    print ("Must provide a file...");
 
40
    raise SystemExit
 
41
  
 
42
  f = open (file_name, "rb")
 
43
  
 
44
  buff_bytes = f.read ()
 
45
  
 
46
  compressed_buff = zlib.compress (buff_bytes)
 
47
  compressed_buff_len = len (compressed_buff)
 
48
  
 
49
  out_str = StringIO ()
 
50
  
 
51
  
 
52
  sane_file_name = file_name.replace (".","_").replace("/","_").replace("__","")
 
53
  out_str.write ("const unsigned char ")
 
54
  out_str.write (sane_file_name)
 
55
  out_str.write ("[] = {")
 
56
  
 
57
  counter = 0
 
58
  
 
59
  for i in range (0, len (compressed_buff)):
 
60
    byte = compressed_buff[i]
 
61
    
 
62
    out_str.write ("0x%02x," % byte)
 
63
    
 
64
    if (counter % 10 == 0):
 
65
      out_str.write ("\n")
 
66
    counter+=1
 
67
  
 
68
  out_str.write("};")
 
69
  
 
70
  out_str.write ("\n\nsize_t %s_len = %i;" % (sane_file_name, compressed_buff_len) )
 
71
  out_str.write ("\n\nsize_t %s_real_len = %i;" % (sane_file_name, len (buff_bytes)) )
 
72
  
 
73
  print (out_str.getvalue())
 
74
 
 
75
main ()