-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.py
More file actions
executable file
·88 lines (71 loc) · 2.67 KB
/
convert.py
File metadata and controls
executable file
·88 lines (71 loc) · 2.67 KB
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
#!/bin/env python3
import datetime
import os
import sys
import argparse
from PIL import Image
def convert_img_to_asm(image, name, colormap):
width, height = image.size
image = image.load()
inc = "\n; Auto generated by {} on {:%d-%m-%Y %H:%M}\n".format(
os.path.basename(__file__),
datetime.datetime.now()
)
asm = str(inc)
uppername = name.upper()
inc += "IMG_{}_WIDTH EQU {}\n".format(uppername, width)
inc += "IMG_{}_HEIGHT EQU {}\n".format(uppername, height)
inc += "IMG_{}_SIZE EQU {}\n".format(uppername, width * height)
inc += "GLOBAL IMG_{}_DATA:BYTE".format(uppername, width * height)
inc += "\n"
asm += "IMG_{}_DATA DB \\\n".format(uppername)
for y in range(0, height):
asm += "\t"
for x in range(0, width):
asm += "{}, ".format(colormap.get(image[x, y], 0))
asm = asm[:-2]
asm += ", \\\n"
asm = asm[:-4]
asm += "\n"
return inc, asm
def hex_to_triple(hexstr):
if (hexstr[0] == "#"):
hexstr = hexstr[1:]
r, g, b = hexstr[0:2], hexstr[2:4], hexstr[4:6]
return tuple([int(c, 16) for c in (r, g, b)])
def main(args):
parser = argparse.ArgumentParser(description='Convert images to assembly')
parser.add_argument('-m', '--map', metavar=('COLOR', 'NR'),
help='map a colour to an integer value', nargs=2,
action='append')
parser.add_argument('-i', '--include', type=argparse.FileType('w'),
default='ASSETS.INC')
parser.add_argument('-a', '--assembly', type=argparse.FileType('w'),
default='ASSETS.ASM')
parser.add_argument('paths', metavar='IMG', type=str,
nargs='+', help='files to convert')
args = parser.parse_args(args[1:])
colormap = {}
print(args)
for mapping in args.map:
[colour, number] = mapping
colour = colour.split(",")
if len(colour) == 1:
colour = hex_to_triple(colour[0])
elif len(colour) == 3:
colour = tuple(colour)
else:
raise RuntimeError(colour, "invalid colour")
colormap[colour] = number
print("Using colourmap:", colormap, "\n")
inc, asm = "", "IDEAL\nP386\nMODEL FLAT, C\nDATASEG\nINCLUDE \"{}\"\n".format(args.include.name)
for path in args.paths:
name, ext = os.path.splitext(os.path.basename(path))
img = Image.open(path)
inc_, asm_ = convert_img_to_asm(img, name, colormap)
inc += inc_; asm += asm_
asm += "\nEND\n"
for text, file in [(asm, args.assembly), (inc, args.include)]:
file.write(text)
if __name__ == "__main__":
main(sys.argv)