-
Notifications
You must be signed in to change notification settings - Fork 1
/
bmp2hex.py
293 lines (248 loc) · 10.1 KB
/
bmp2hex.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/env python
# @file bmp2hex.py
# @ingroup util
# A script for converting a 1-bit bitmap to HEX for use in an Arduino sketch.
#
# The BMP format is well publicized. The byte order of the actual bitmap is a
# little unusual. The image is stored bottom to top, left to right. In addition,
# The pixel rows are rounded to DWORDS which are 4 bytes long. SO, to convert this
# to left to right, top to bottom, no byte padding. We have to do some calculations
# as we loop through the rows and bytes of the image. See below for more
#
# Usage:
# >>>bmp2hex.py [-i] [-r] [-n] [-d] [-x] [-w <bytes>] [-b <size-bytes>] <infile> <tablename>
#
# @param infile The file to convert.
# @param tablename The name of the table to create
# @param raw "-r", bitmap written as raw table [optional]
# @param invert "-i", to invert image pixel colors [optional]
# @param tablewidth "-w <bytes>, The number of characters for each row of the output table [optional]
# @param sizebytes "-b <bytes>, Bytes = 0, 1, or 2. 0 = auto. 1 = 1-byte for sizes. 2 = 2-byte sizes (big endian) [optional]
# @param named "-n", use a names structure [optional]
# @param double "-d", use double bytes rather than single ones [optional]
# @param xbm "-x", use XBM format (bits reversed in byte) [optional]
# @param version "-v", returns version number
#
# @author Robert Gallup 2016-02
#
# Author: Robert Gallup (bg@robertgallup.com)
# License: MIT Opensource License
#
# Copyright 2016-2022 Robert Gallup
#
import argparse
import array
import logging
import math
import os
import random
import struct
import sys
import textwrap
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
class DEFAULTS(object):
STRUCTURE_NAME = 'GFXMeta'
VERSION = '2.3.5'
def main():
# Default parameters
infile = ""
tablename = ""
tablewidth = 16
sizebytes = 0
invert = False
raw = False
named = False
double = False
xbm = False
version = False
# Set up parser and handle arguments
parser = argparse.ArgumentParser()
# parser.add_argument ("infile", help="The BMP file(s) to convert", type=argparse.FileType('r'), nargs='+', default=['-'])
parser.add_argument("infile", help="The BMP file(s) to convert",
type=argparse.FileType('r'), nargs='*', default=['-'])
parser.add_argument(
"-r", "--raw", help="output all data in raw table format", action="store_true")
parser.add_argument(
"-i", "--invert", help="invert bitmap pixels", action="store_true")
parser.add_argument(
"-w", "--width", help="output table width in hex bytes [default: 16]", type=int)
parser.add_argument(
"-b", "--bytes", help="set byte width of BMP sizes: 0=auto, 1, or 2 (big endian) [default: 0]", type=int)
parser.add_argument("-n", "--named", help="use named structure (" +
DEFAULTS.STRUCTURE_NAME + ") for data", action="store_true")
# parser.add_argument ("-d", "--double", help="define data in 'words' rather than bytes", action="store_true")
parser.add_argument(
"-x", "--xbm", help="use XBM bit order (low order bit is first pixel of byte)", action="store_true")
parser.add_argument(
"-v", "--version", help="echo the current bmp2hex version", action="store_true")
args = parser.parse_args()
# Required arguments
infile = args.infile
# Options
if args.raw:
raw = args.raw
if args.invert:
invert = args.invert
if args.width:
tablewidth = args.width
if args.bytes:
sizebytes = args.bytes % 3
if args.named:
named = args.named
# if args.double:
# double = args.double
double = False
if args.xbm:
xbm = args.xbm
if args.version:
logging.debug('// bmp2hex version ' + DEFAULTS.VERSION)
# Output named structure, if requested
if (named):
logging.debug('struct ' + DEFAULTS.STRUCTURE_NAME + ' {')
logging.debug(' unsigned int width;')
logging.debug(' unsigned int height;')
logging.debug(' unsigned int bitDepth;')
logging.debug(' int baseline;')
logging.debug(' ' + getDoubleType(double)[0] + 'pixel_data;')
logging.debug('};')
logging.debug('')
# Do the work
for f in args.infile:
if f == '-':
sys.exit()
logging.debug(
f'{f.name} {tablewidth} {sizebytes} {invert} {raw} {named} {double} {xbm}')
bmp2hex(f.name, tablewidth, sizebytes, invert, raw, named, double, xbm)
def reflect(a):
"""Reverse pixels in a byte."""
r = 0
for i in range(8):
r <<= 1
r |= (a & 0x01)
a >>= 1
return (r)
def getDoubleType(d):
"""Return a tuple with the C data type name and length for double and short data types."""
if d:
dType = 'uint16_t' + ' *'
dLen = 2
else:
dType = 'uint8_t' + ' *'
dLen = 1
return (dType, dLen)
def unsupported_file_error(msg):
"""Exit with unsupported file format message"""
sys.exit("error: " + msg)
# Main conversion function
def bmp2hex(infile, tablewidth, sizebytes, invert, raw, named, double, xbm):
"""Comvert supported BMP files to hex string output"""
# Set up some variables to handle the "-d" option
(pixelDataType, dataByteLength) = getDoubleType(double)
# Set the table name to the uppercase root of the file name
tablename = os.path.splitext(infile)[0].upper()
# Convert tablewidth to characters from hex bytes
tablewidth = int(tablewidth) * 6
# Initilize output buffer
outstring = ''
# Open File
fin = open(os.path.expanduser(infile), "rb")
uint8_tstoread = os.path.getsize(os.path.expanduser(infile))
valuesfromfile = array.array('B')
try:
valuesfromfile.fromfile(fin, uint8_tstoread)
finally:
fin.close()
# Get bytes from file
values = valuesfromfile.tolist()
# Exit if it's not a Windows BMP
if ((values[0] != 0x42) or (values[1] != 0x4D)):
unsupported_file_error("Not BMP file.")
# Unpack header values using struct
# Note: bytes(bytearray)) is used for compatibility with python < 2.7.3
dataOffset, \
headerSize, \
pixelWidth, \
pixelHeight, \
colorPlanes, \
bitDepth, \
compression, \
dataSize = struct.unpack("<2L2l2h2L", bytes(bytearray(values[10:38])))
# Check other conditions for compatibility
if bitDepth > 16:
unsupported_file_error(
"unsupported bit depth (max 16): " + str(bitDepth))
elif pixelWidth < 0:
unsupported_file_error(
"unsupported negative pixel width: " + str(pixelWidth))
elif pixelHeight < 0:
unsupported_file_error(
"unsupported negative pixel height: " + str(pixelHeight))
# Calculate line width in bytes and padded byte width (each row is padded to 4-byte multiples)
byteWidth = int(math.ceil(float(pixelWidth * bitDepth)/8.0))
paddedWidth = int(math.ceil(float(byteWidth)/4.0)*4.0)
# For auto (sizebytes = 0), set sizebytes to 1 or 2, depending on size of the bitmap
if (sizebytes == 0):
if (pixelWidth > 255) or (pixelHeight > 255):
sizebytes = 2
else:
sizebytes = 1
# The invert byte is set based on the invert command line flag (but, the logic is reversed for 1-bit files)
invertbyte = 0xFF if invert else 0x00
if (bitDepth == 1):
invertbyte = invertbyte ^ 0xFF
# Output the hex table declaration
# With "raw" output, output just an array of chars
if (raw):
# Output the data declaration
logging.debug('PROGMEM unsigned char const ' + tablename + ' [] = {')
# Output the size of the BMP
if (not (sizebytes % 2)):
logging.debug("{0:#04X}".format((pixelWidth >> 8) & 0xFF) + ", " + "{0:#04X}".format(pixelWidth & 0xFF) + ", " +
"{0:#04X}".format((pixelHeight >> 8) & 0xFF) + ", " + "{0:#04X}".format(pixelHeight & 0xFF) + ",")
else:
logging.debug("{0:#04X}".format(pixelWidth & 0xFF) + ", " +
"{0:#04X}".format(pixelHeight & 0xFF) + ",")
elif (named):
logging.debug('PROGMEM ' + getDoubleType(double)
[0] + ' const ' + tablename + '_PIXELS[] = {')
elif (xbm):
logging.debug('#define ' + tablename + '_width ' + str(pixelWidth))
logging.debug('#define ' + tablename + '_height ' + str(pixelHeight))
logging.debug('PROGMEM ' + getDoubleType(double)
[0] + ' const ' + tablename + '_bits[] = {')
else:
logging.debug('PROGMEM const struct {')
logging.debug(' unsigned int width;')
logging.debug(' unsigned int height;')
logging.debug(' unsigned int bitDepth;')
logging.debug(' ' + pixelDataType +
'pixel_data[{0}];'.format(round(byteWidth * pixelHeight / dataByteLength)))
logging.debug('} ' + tablename + ' = {')
logging.debug('{0}, {1}, {2}, {{'.format(
pixelWidth, pixelHeight, bitDepth))
# Generate HEX bytes for pixel data in output buffer
try:
for i in range(pixelHeight):
for j in range(byteWidth):
ndx = dataOffset + ((pixelHeight-1-i) * paddedWidth) + j
v = values[ndx] ^ invertbyte
if (xbm):
v = reflect(v)
# logging.debug ("{0:#04x}".format(v))
outstring += "{0:#04x}".format(v) + ", "
# Wrap the output buffer. logging.debug. Then, finish.
finally:
outstring = textwrap.fill(outstring[:-2], tablewidth)
logging.debug(outstring)
if (named):
logging.debug('};')
logging.debug(DEFAULTS.STRUCTURE_NAME + ' const ' + tablename + ' = {{{0}, {1}, {2}, 0, '.format(pixelWidth, pixelHeight, bitDepth) +
pixelDataType + tablename + "_PIXELS};\n\n")
else:
if (not (raw or xbm)):
logging.debug("}")
logging.debug("};")
return outstring
# Only run if launched from commandline
# if __name__ == '__main__':
# main()