python script to convert images to header files

This commit is contained in:
2026-08-07 23:13:02 +02:00
parent 5f63962f31
commit 16b7355361

56
bmp2h.py Normal file
View File

@@ -0,0 +1,56 @@
from PIL import Image
import sys
def get_bytestring(fname):
bmp_name = fname.rsplit(".", 1)[0]
print("""#pragma once
#include <esp-gfx/gfx.h>
#include <stdint.h>
const uint8_t """ + bmp_name + """_data[] PROGMEM = {""", end="")
with Image.open(fname) as im:
w = im.size[0]
h = im.size[1]
im = im.convert('L')
pix = im.load()
for i in range(w*h // 8):
x = (i * 8) % w
y = i // (w // 8)
b = 0
if x == 0:
print("")
for bit in range(8):
if x + bit >= w: break
if y >= h: break
if pix[x + bit, y] < 127:
b += 1 << bit
print("\t", hex(b), end=", ")
print("""
};
const gfx_bitmap_t """ + bmp_name + """ = {
\t.width = """ + str(w) + """,
\t.height = """ + str(h) + """,
\t.data = (uint8_t*)""" + bmp_name + """_data,
};
""")
if __name__ == "__main__":
script_name = sys.argv[0]
if len(sys.argv) > 1:
get_bytestring(sys.argv[1])
else:
print("\n{} - image to header file converter, to be used with esp-gfx library\n\nUsage: {} <image>\n".format(script_name, script_name))
print("\tUse redirection ({} <opts> > header.h) to save the header".format(script_name))
print("\tThis script needs Pillow installed to work")