经常需要使用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)