图片转RGB565格式.c文件

前提有py环境

安装py脚本:pip install pillow numpy
执行脚本:python convert_to_rgb565.py

运行后转换当前目录下所有图片,生成一个.c一个.h

convert_to_rgb565.py

import os
from PIL import Image
import numpy as np
import re

def sanitize_filename(filename):
    # 将空格和特殊符号替换为下划线
    return re.sub(r'[ @]', '_', filename)

def convert_image_to_rgb565(image_path):
    img = Image.open(image_path)
    img = img.convert('RGB')
    img_data = np.array(img)
    
    rgb565_array = []
    for pixel in img_data.reshape(-1, 3):
        r, g, b = pixel
        rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
        rgb565_array.append(rgb565 & 0xFF)         # 低8位
        rgb565_array.append((rgb565 >> 8) & 0xFF)  # 高8位
    
    return rgb565_array, img.width, img.height

def generate_c_and_h_files(images_folder):
    c_file_content = '#include "image_data.h"\n\n'  # 加入头文件引用
    h_file_content = '#ifndef IMAGE_DATA_H\n#define IMAGE_DATA_H\n\n'
    
    supported_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff')

    for filename in os.listdir(images_folder):
        if filename.lower().endswith(supported_formats):  # 支持多种格式
            sanitized_name = sanitize_filename(os.path.splitext(filename)[0])
            image_path = os.path.join(images_folder, filename)
            rgb565_data, width, height = convert_image_to_rgb565(image_path)
            array_size = len(rgb565_data)
            
            # 生成C文件内容
            c_file_content += f'const uint8_t {sanitized_name}_pic[{array_size}] = {{\n'
            for i, val in enumerate(rgb565_data):
                c_file_content += f'0x{val:02X}, '
                if (i + 1) % 12 == 0:
                    c_file_content += '\n'
            c_file_content += '};\n\n'
            c_file_content += f'const uint16_t {sanitized_name}_width = {width};\n'
            c_file_content += f'const uint16_t {sanitized_name}_height = {height};\n\n'
            
            # 生成H文件内容
            h_file_content += f'extern const uint8_t {sanitized_name}_pic[{array_size}];\n'
            h_file_content += f'extern const uint16_t {sanitized_name}_width;\n'
            h_file_content += f'extern const uint16_t {sanitized_name}_height;\n\n'

    # 结束H文件
    h_file_content += '#endif // IMAGE_DATA_H\n'
    
    # 保存C文件
    with open(os.path.join(images_folder, 'image_data.c'), 'w') as c_file:
        c_file.write(c_file_content)
    
    # 保存H文件
    with open(os.path.join(images_folder, 'image_data.h'), 'w') as h_file:
        h_file.write(h_file_content)

# 调用函数
generate_c_and_h_files(os.getcwd())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值