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
|
#!/usr/bin/env python3
__version__ = "1.0"
from argparse import ArgumentParser
from PIL import Image
# firmware
CPC_PAL = (
[0, 0, 0],
[0, 0, 128],
[0, 0, 255],
[128, 0, 0],
[128, 0, 128],
[128, 0, 255],
[255, 0, 0],
[255, 0, 128],
[255, 0, 255],
[0, 128, 0],
[0, 128, 128],
[0, 128, 255],
[128, 128, 0],
[128, 128, 128],
[128, 128, 255],
[255, 128, 0],
[255, 128, 128],
[255, 128, 255],
[0, 255, 0],
[0, 255, 128],
[0, 255, 255],
[128, 255, 0],
[128, 255, 128],
[128, 255, 255],
[255, 255, 0],
[255, 255, 128],
[255, 255, 255],
)
SW_TO_HW = (
0x54,
0x44,
0x55,
0x5C,
0x58,
0x5D,
0x4C,
0x45,
0x4D,
0x56,
0x46,
0x57,
0x5E,
0x40,
0x5F,
0x4E,
0x47,
0x4F,
0x52,
0x42,
0x53,
0x5A,
0x59,
0x5B,
0x4A,
0x43,
0x4B,
)
def main():
parser = ArgumentParser(
description="PNG to CPC palette (firmware)",
epilog="Copyright (C) 2015-2023 Juan J Martinez <jjm@usebox.net>",
)
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__
)
parser.add_argument("--header", dest="header", action="store_true")
parser.add_argument("--hardware", dest="hardware", action="store_true")
parser.add_argument("image", help="image to convert")
parser.add_argument(
"pal_dump",
help="filename for the palette dump (variable if header flag is set)",
)
args = parser.parse_args()
try:
image = Image.open(args.image)
except IOError:
parser.error("failed to open the image")
if image.mode != "P":
parser.error("not an indexed image (no palette)")
palette = image.getpalette()
if not palette:
parser.error("failed to extract the palette (is this an indexed image?)")
rgb = []
for i in range(0, 16 * 3, 3):
c = palette[i : i + 3]
if c not in CPC_PAL:
parser.error("%r not in the CPC palette" % c)
rgb.append(c)
out = [CPC_PAL.index(c) for c in rgb]
if len(out) < 16:
out.extend([0 for _ in range(16 - len(out))])
if args.hardware:
out = [SW_TO_HW[c] for c in out[:]]
if args.header:
print("/* %s palette */" % ("hardware" if args.hardware else "firmware"))
print("#ifdef LOCAL")
print(
"const unsigned char %s[] = { %s };\n"
% (args.pal_dump, ", ".join([hex(c) for c in out]))
)
print("#else")
print("extern const unsigned char %s[];\n" % (args.pal_dump))
print("#endif")
else:
with open(args.pal_dump, "wb") as fd:
fd.write(bytearray(out))
if __name__ == "__main__":
main()
|