1
0
Fork 0
mirror of https://github.com/radex/radmatrix.git synced 2024-10-30 00:44:51 +00:00
radmatrix/firmware/scripts/gfx_convert.py

91 lines
2.2 KiB
Python
Raw Normal View History

2024-03-23 18:06:39 +00:00
# read gfx folder
import os
import sys
import PIL
from PIL import Image
def get_all_gfx():
gfx = []
2024-03-23 19:07:48 +00:00
for root, dirs, files in os.walk("gfx-badapple"):
2024-03-23 18:06:39 +00:00
for file in files:
2024-03-23 19:07:48 +00:00
if file.startswith("."):
continue
2024-03-23 18:06:39 +00:00
# file name without extention
name = os.path.splitext(file)[0]
gfx.append((name, os.path.join(root, file)))
gfx.sort()
return gfx
def to_code(name, path):
img = Image.open(path)
img = img.convert("1", dither=Image.Dither.FLOYDSTEINBERG)
w, h = img.size
code = f"uint32_t gfx_{name}[{h}] = {'{'}\n"
for y in range(h):
code += " 0b"
for x in range(w):
px = img.getpixel((x, y))
2024-03-23 19:07:48 +00:00
code += '0' if px == 0 else '1'
2024-03-23 18:06:39 +00:00
code += ",\n"
code += "};\n\n"
return code
2024-03-23 21:09:46 +00:00
def generate_gfx():
2024-03-23 18:06:39 +00:00
gfx = get_all_gfx()
gfx_code = ''.join(to_code(name, path) for name, path in gfx)
header = f"#pragma once\n#include <Arduino.h>\n\n/* DO NOT MODIFY - AUTOGENERATED! */\n\n"
index = f"uint32_t* frames[{len(gfx)}] = {'{'}\n"
for name, _ in gfx:
index += f" gfx_{name},\n"
index += "};\n"
with open("src/gfx.h", "w") as f:
f.write(header)
f.write("#define GFX_COUNT " + str(len(gfx)) + "\n\n")
f.write(gfx_code)
f.write(index)
print("gfx.h generated!")
2024-03-23 21:09:46 +00:00
def png_to_code(name, path):
file = open(path, "rb")
data = file.read()
size = len(data)
code = f"uint8_t png_{name}[{size}] = {'{'}"
for i in range(size):
code += f"0x{data[i]:02x},"
code += "};\n\n"
return code
def generate_png_gfx():
gfx = get_all_gfx()
gfx_code = ''.join(png_to_code(name, path) for name, path in gfx)
header = f"#pragma once\n#include <Arduino.h>\n\n/* DO NOT MODIFY - AUTOGENERATED! */\n\n"
index = f"uint8_t* png_frames[{len(gfx)}] = {'{'}\n"
for name, _ in gfx:
index += f" png_{name},\n"
index += "};\n"
with open("src/gfx_png.h", "w") as f:
f.write(header)
f.write("#define PNG_COUNT " + str(len(gfx)) + "\n\n")
f.write(gfx_code)
f.write(index)
print("gfx_png.h generated!")
if __name__ == "__main__":
generate_gfx()
generate_png_gfx()