您的位置:首页 > 编程语言 > Python开发

[MTK FP]用Python把二进制音频/图片文件转为数组

2013-04-08 22:16 459 查看
在MTK平台,音频/图片文件基本以数组的形式存在,一般MTK会提供工具来转换音频/图片文件为数组。

这里使用python来实现把二进制文件转为数组,目的有两个:

1. 把python程序转换的二进制数组替换目前代码中已有的数组,可以实现快速验证;

2. 对于比较大的二进制文件,MTK提供的工具未必支持转换,这个时候就可以用这里的python程序来转换。

下面是python程序,替换掉input_f和output_f为你输入的二进制文件盒输出数组的文件名称即可:

# -*- coding: utf-8 -*-
# It is ok at python-3.3.1rc1.msi installer condition.

import os

def read_data_from_binary_file(filename, list_data):
f = open(filename, 'rb')
f.seek(0, 0)
while True:
t_byte = f.read(1)
if len(t_byte) == 0:
break
else:
list_data.append("0x%.2X" % ord(t_byte))

def write_data_to_text_file(filename, list_data):
f_output = open(filename, 'w+')
f_output.write('__align(4) const U8 temp[] = \n')
f_output.write('{\n    ')

count = 0
lenth = len(list_data)
for data in list_data:
count += 1
if count != lenth:
f_output.write(data+', ')
else:
f_output.write(data)
if count%16==0:
f_output.write('\n    ')
f_output.write('\n};')
f_output.close()

list_data = []
input_f = r'python.gif'
output_f = r'python.txt'
read_data_from_binary_file(input_f, list_data)
write_data_to_text_file(output_f, list_data)


上面示例中的python.gif文件:



生成的数组如下:

__align(4) const U8 temp[] =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0E, 0x00, 0x0F, 0x00, 0xA2, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFF, 0xFF, 0x00, 0x80, 0x80, 0x00, 0x00,
0x00, 0xFF, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x03, 0x00, 0x2C, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x00, 0x0F, 0x00, 0x40, 0x03, 0x42, 0x38, 0x0A, 0xAC, 0xFE, 0x40, 0x08, 0x06,
0x42, 0x01, 0x8B, 0x95, 0xCB, 0xF7, 0x7D, 0x43, 0x65, 0x75, 0x1B, 0xB6, 0x18, 0x80, 0x71, 0x99,
0x8E, 0x18, 0xBC, 0x01, 0x50, 0x82, 0xCC, 0x3B, 0x87, 0xDF, 0x02, 0xEF, 0x2C, 0x7E, 0x83, 0x21,
0x00, 0x41, 0x28, 0xCB, 0x2D, 0x3C, 0x9E, 0x11, 0xAB, 0x36, 0x89, 0x55, 0x8C, 0xA1, 0x89, 0x68,
0x26, 0x33, 0x4D, 0x57, 0x9A, 0xDC, 0x15, 0x19, 0x1B, 0x24, 0x00, 0x00, 0x3B
};


PS:目前MTK平台图片文件都有header,所以转换的数组要加上header才能生效,这里对于此只是一个示例,需要实现全功能的人可以自行修改程序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: