I read the JPEG image file and saved its bits in a text file. Now I want to convert back to a valid JPEG image using these bits in a text file. I tried to write a binary file, but it does not extract the image file.
Please guide me in the right direction. I have been in this for a couple of days, but so far no luck.
Here is my code for writing a jpg file:
int length;
unsigned char *inData;
char Buffer[9];
int c = 0, x;
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){
Buffer[c] = inData;
} else {
fwrite(&Buffer, sizeof(Buffer), 1, writer);
c = 0;
}
c++;
}
fclose(reader);
fclose(writer);
Here is a snippet of code to read input.JPG and write its bit to 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);
}
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);
}
Thank,
-Sam