搜档网
当前位置:搜档网 › C语言读取png数据写到文件中

C语言读取png数据写到文件中



#include
#include
#include
#include
#include

#define SAFE_FREE(x) {free(x);x=NULL;}

#define BUFFER_SIZE 1024*1024 //1M

int main(int p1, char **p2)
{
unsigned int offset = 0;

FILE *sFile = fopen("F:\\boom_superman\\test123.png", "rb");
FILE *dFile = fopen("F:\\boom_superman\\123.txt", "w");
FILE *txtFile = fopen("F:\\boom_superman\\456.txt", "w");

unsigned char *buf = (unsigned char *)malloc(BUFFER_SIZE);

size_t nSize = fread(buf, 1, BUFFER_SIZE, sFile);

//检查是不是PNG
unsigned char png[] = {0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa};
for (; offset<8; offset++)
{
if (buf[offset] != png[offset])
{
printf("我只处理png,这不合我的胃口\n");
system("PAUSE");
exit(1);
}
}

//打印出所有 数据块 的 名字
while(offset < nSize)
{
unsigned int dataLen = 0; //数据长度
for (unsigned int i=offset+4; offset{
dataLen += buf[offset]* pow((double)256, (int)(i-offset-1));
}

//如果是图像数据, 就写到另一个文件中
if (buf[offset] == 'I' && buf[offset+1] == 'D' && buf[offset+2] == 'A' && buf[offset+3] == 'T')
{

for (int i=0; i{
fprintf(txtFile, "0x%x ", buf[offset + 4 + i]);
}

fprintf(txtFile, "\n\n\n\n");

}

for (char i=0; i<4; i++)//写名字
{
fprintf(dFile, "%c", buf[offset++]);
}
fprintf(dFile, "\n");
offset += (dataLen + 4); //跳过数据和CRC校验码
}

fclose(sFile);
fclose(dFile);
fclose(txtFile);

SAFE_FREE(buf);

return 0;
}

相关主题