我读取 JPEG 图像文件并将其位存储到文本文件中。现在我想使用文本文件中的这些位转换回有效的 JPEG 图像。我试过写一个二进制文件,但它没有检索到图像文件。
请引导我走向正确的方向。这几天我一直在努力解决这个问题,但到目前为止还没有运气。
这是我编写 JPG 文件的代码:
int length;
unsigned char *inData;
char Buffer[9];
int c = 0, x;
/* file.txt has single bit per line. */
FILE *reader = fopen(file.txt, "r");
FILE *writer = fopen("output.JPG","wb");
fseek(reader, 0, SEEK_END);
length=ftell(reader);
fseek(reader, 0, SEEK_SET);
for(x=0; x < length; x++){
fscanf(reader, "%d", &inData);
if(c <= 8){ /* reading 8-bits */
Buffer[c] = inData;
} else {
fwrite(&Buffer, sizeof(Buffer), 1, writer);
c = 0;
}
c++;
}
fclose(reader);
fclose(writer);
这是读取 input.JPG 并将其位写入 file.txt 的代码片段
char *buffer;
int fileLen;
FILE *file = fopen("inputIM.JPG", "rb");
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
buffer=(char *)malloc(fileLen+1);
fread(buffer, fileLen, 1, file);
fclose(file);
convertToBit(&buffer, fileLen);
free(buffer);
}
// convert buffer data to bits and write them to a text file
convertToBit(void *buffer, int length)
{
int c=0;
int SIZE = length * 8;
unsigned char bits[SIZE + 1];
unsigned char mask = 1;
unsigned char byte ;
int i = 0;
FILE *bitWRT = fopen("file.txt", "w");
for (c=0;c<length;c++)
{
byte = ((char *)&buffer)[c];
for(i = 0; i < 8; i++){
bits[i] = (byte >> i) & mask;
fprintf(bitWRT, "%d\n", bits[i]);
}
}
fclose(bitWRT);
}
谢谢,
-山姆