IMX6U-Game/tools/png_to_header.py

63 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
将 PNG 图片转换为 C 头文件uint32_t 像素数组)。
用法:
python tools/png_to_header.py input.png output.h [var_name]
像素格式: (R << 24) | (G << 16) | (B << 8) | A
与 FrameBuffer 的 uint32_t 格式一致。
如果图片没有 alpha 通道A 默认为 0xFF。
"""
import sys
import os
from PIL import Image
def convert(input_path: str, output_path: str, var_name: str):
img = Image.open(input_path).convert("RGBA")
w, h = img.size
pixels = list(img.getdata()) if not hasattr(img, "get_flattened_data") else list(img.get_flattened_data())
packed = []
for r, g, b, a in pixels:
packed.append((r << 24) | (g << 16) | (b << 8) | a)
with open(output_path, "w", encoding="utf-8") as f:
f.write("// Auto-generated by tools/png_to_header.py\n")
f.write(f"#pragma once\n#include <cstdint>\n\n")
f.write(f"static const int32_t {var_name}_width = {w};\n")
f.write(f"static const int32_t {var_name}_height = {h};\n\n")
f.write(f"static const uint32_t {var_name}_pixels[] = {{\n")
for i in range(0, len(packed), 16):
chunk = packed[i : i + 16]
line = ", ".join(f"0x{p:08X}" for p in chunk)
f.write(f" {line},\n")
f.write("};\n")
def main():
if len(sys.argv) < 3:
print(f"用法: {sys.argv[0]} input.png output.h [var_name]")
sys.exit(1)
input_path = sys.argv[1]
output_path = sys.argv[2]
if len(sys.argv) >= 4:
var_name = sys.argv[3]
else:
# 从文件名生成变量名: player_idle.png -> player_idle
var_name = os.path.splitext(os.path.basename(input_path))[0]
convert(input_path, output_path, var_name)
print(f"已生成: {output_path} (var: {var_name}, 像素数: {var_name}_width * {var_name}_height)")
if __name__ == "__main__":
main()