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
|
#!/usr/bin/env python3
from argparse import ArgumentParser
import subprocess
import os
from PIL import Image
__version__ = "1.0"
ld = os.environ.get("LD", "i586-pc-msdosdjgpp-ld")
strip = os.environ.get("STRIP", "i586-pc-msdosdjgpp-strip")
def main():
parser = ArgumentParser(
description="PNG to palette .o",
epilog="Copyright (C) 2023 Juan J Martinez <jjm@usebox.net>",
)
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__
)
parser.add_argument("image", help="image to convert")
parser.add_argument("output", help="object name for the palette")
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")
tmp = args.output.rstrip(".o")
with open(tmp, "wb") as fd:
fd.write(bytearray(palette))
fd.flush()
# create an object file from the binary
rc = subprocess.call(
[
ld,
"-r",
"-b",
"binary",
"-o",
args.output,
tmp,
]
)
os.unlink(tmp)
if rc != 0:
parser.error("Failed to run %s" % ld)
# strip unwanted symbols
rc = subprocess.call([strip, "-w", "-K", "*_%s_*" % tmp, args.output])
if rc != 0:
parser.error("Failed to run %s" % ld)
if __name__ == "__main__":
main()
|