From http://www.jwz.org/xscreensaver/xscreensaver-5.39.tar.gz
[xscreensaver] / utils / bin2c
1 #!/bin/sh
2 # Copyright © 2018 Jamie Zawinski <jwz@jwz.org>
3 #
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation.  No representations are made about the suitability of this
9 # software for any purpose.  It is provided "as is" without express or 
10 # implied warranty.
11 #
12 # Converts a binary file to a C source code string, e.g., to embed the
13 # contents of a PNG file by including a .h file.
14 #
15 # Created:  7-Feb-2018.
16
17 usage () {
18   echo "usage: $0 in.png out_png.h" >&2
19   exit 1
20 }
21
22 if [ $# != 2 ]; then usage; fi
23
24 IN="$1"
25 OUT="$2"
26
27 NAME=`echo "$OUT" | sed \
28   -e 's@^.*/@@' \
29   -e 's/\.[^.]*$//' \
30   -e 's/[-.]/_/g' \
31   -e 's/^\([^a-z]\)/_\1/'`;
32
33 if [ x"$PERL" = "x" ]; then PERL=perl ; fi
34
35 # On Linux, we could do this and put the raw image into a .o data segment:
36 #       $(LD) -r -b binary $< -o $@
37 # but that doesn't work on MacOS.
38
39 exec $PERL -0 -pe "
40   BEGIN { print \"#ifdef __GNUC__\\n\";
41           print \"__extension__\\n\";
42           print \"#endif\\n\";
43           print \"static const unsigned char ${NAME}[] =\\n \\\"\"; }
44   END   { print \"\\\";\\n\"; }
45   s/([^ -\041\043-\076\100-\133\135-\176])/sprintf(\"\\\\%03o\",ord(\$1))/gse;"\
46   < "$IN" > "$OUT"