#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2024/01/13 17:37:11 +0900> """ png image to c header file Usage: python png2bits.py -i input.png --label label_name > image.h Windows10 x64 22H2 + Python 3.10.10 64bit + Pillow 10.1.0 """ import argparse import os import sys from PIL import Image def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--infile", required=True, help="PNG image file") parser.add_argument("--label", help="symbol name") args = parser.parse_args() infile = args.infile if os.path.isfile(infile): print("/* infile: %s */" % infile) else: print("Error: Not found %s" % infile) sys.exit() if not args.label: label = infile.replace(".", "_") label = label.replace(" ", "_") else: label = args.label im = Image.open(infile).convert("L") im.point(lambda x: 0 if x < 128 else x) w, h = im.size print("static unsigned int %s_width = %d;" % (label, w)) print("static unsigned int %s_height = %d;\n" % (label, h)) print("static unsigned char %s[] = {" % (label)) count = 0 for y in range(h - 1, -1, -1): buf = [] for i in range(int(w / 8)): buf.append(0) if (w % 8) != 0: buf.append(0) for x in range(w): v = im.getpixel((x, y)) if v > 128: buf[int(x / 8)] |= 1 << (7 - (x % 8)) s = "" for v in buf: s += "0x%s," % format(v, "02x") count += 1 print(" %s // %d" % (s, y)) print("};\n") print("static unsigned int %s_len = %d;" % (label, count)) if __name__ == "__main__": main()