|
| 1 | +from PIL import Image |
| 2 | +import numpy as np |
| 3 | +import sys |
| 4 | + |
| 5 | +def rgb888_to_rgb565(r, g, b): |
| 6 | + """Convert from RGB888 to RGB565.""" |
| 7 | + return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) |
| 8 | + |
| 9 | +def convert_image_to_rgb565_a8_header(png_filepath, header_filepath): |
| 10 | + """Convert a PNG image to RGB565 with Alpha format and save as a C header file in uint8_t array format.""" |
| 11 | + img = Image.open(png_filepath).convert('RGBA') |
| 12 | + pixels = np.array(img) |
| 13 | + height, width, _ = pixels.shape |
| 14 | + |
| 15 | + with open(header_filepath, 'w') as header_file: |
| 16 | + header_file.write("#ifndef IMAGE_H\n") |
| 17 | + header_file.write("#define IMAGE_H\n\n") |
| 18 | + header_file.write("#include <stdint.h>\n\n") |
| 19 | + header_file.write(f"static const uint32_t image_width = {width};\n") |
| 20 | + header_file.write(f"static const uint32_t image_height = {height};\n") |
| 21 | + header_file.write("static const uint8_t image_data[] = {\n") |
| 22 | + |
| 23 | + for y in range(height): |
| 24 | + for x in range(width): |
| 25 | + r, g, b, a = pixels[y, x] |
| 26 | + rgb565 = rgb888_to_rgb565(r, g, b) |
| 27 | + # Write RGB565 in two parts (high byte, low byte) and then Alpha |
| 28 | + header_file.write(f" 0x{rgb565 >> 8:02X}, 0x{rgb565 & 0xFF:02X}, 0x{a:02X},") |
| 29 | + header_file.write("\n") |
| 30 | + |
| 31 | + header_file.write("};\n\n") |
| 32 | + header_file.write("#endif // IMAGE_H\n") |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + if len(sys.argv) != 3: |
| 36 | + print("Usage: python script.py input.png output_image.h") |
| 37 | + sys.exit(1) |
| 38 | + |
| 39 | + png_filepath = sys.argv[1] |
| 40 | + header_filepath = sys.argv[2] |
| 41 | + convert_image_to_rgb565_a8_header(png_filepath, header_filepath) |
0 commit comments