图片批量转换为C语言数组工具

经常需要使用emWin的GUI Builder工具把图片转换为C语言数组,但这个工具每次只能添加一个图片文件,无法批量处理。就用Python写了一个批量转换的小工具。

# encoding:utf-8

import os
import shutil

img_out_c = list()


def img_to_c_string(image_path, img_name):
    with open(image_path, 'rb') as img_file:
        binary_file = img_file.read()

        # img data
        img_out_c.append("/*********************************************************************\n*\n*  name: %s\n*/" % (img_name))
        img_out_c.append("static const uint8_t %s_%s[%s] = {" % (img_name[-3:], img_name[:-4].replace(' ', '_').replace('-', '_'), os.path.getsize(image_path)))

        for x in range(int(len(binary_file) / 20)):
            part = binary_file[20 * x: 20 * x + 20]
            img_out_c.append("    0x" + ", 0x".join(format(x, "02X") for x in part) + ',')
        if len(binary_file) % 20 != 0:
            part = binary_file[int(len(binary_file) / 20) * 20:len(binary_file)]
            img_out_c.append("    0x" + ", 0x".join(format(x, "02X") for x in part))
        img_out_c.append("};\n")


def generate_c_code(env_dir):
    out_path = os.path.join(env_dir, "img_out.c")
    if os.path.isfile(out_path):
        os.remove(out_path)
    with open(out_path, 'w') as c_file:
        for bmp_line in img_out_c:
            c_file.write(bmp_line + '\n')
        c_file.write('\n')


if __name__ == '__main__':
    env_dir = os.path.dirname(os.path.realpath(__file__))
    bmp_dir = os.path.join(env_dir, "IMG")
    if os.path.exists(bmp_dir):
        bmp_list = os.listdir(bmp_dir)
        for img_file in bmp_list:
            bmp_path = os.path.join(bmp_dir, img_file)
            print(bmp_path)
            img_to_c_string(bmp_path, img_file)
        generate_c_code(env_dir)








 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值