代码改变世界

python 取字模

2025-07-04 21:15  qgbo  阅读(11)  评论(0)    收藏  举报
from PIL import Image

def convert_image_to_c_array(image_path):
    # 打开图片
    image = Image.open(image_path)
    width, height = image.size

    # 将图片转换为 RGB 模式
    image = image.convert('RGB')

    # 获取图片的像素数据
    pixels = list(image.getdata())

    # 构建 C 数组的字符串
    c_array = "static const unsigned char bitmap_bytes[] = {\n"
    for i, pixel in enumerate(pixels):
        r, g, b = pixel
        c_array += f"0x{r:02x}, 0x{g:02x}, 0x{b:02x}"
        if i < len(pixels) - 1:
            c_array += ", "
        if (i + 1) % 10 == 0:
            c_array += "\n"
    c_array += "\n};\n"

    # 添加图片的宽度和高度信息
    c_array = f"// Image width: {width}, height: {height}\n" + c_array

    return c_array

def main():
    image_path = input("请输入图片的路径: ")
    c_array = convert_image_to_c_array(image_path)

    # 保存到文件
    output_file = "bitmap.c"
    with open(output_file, "w") as f:
        f.write(c_array)
    print(f"转换结果已保存到 {output_file}")

if __name__ == "__main__":
    main()