Write jpg image file in C

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.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);

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);
}

// 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);
}

Thank,

-Sam

+3
source share
2 answers

Try rewriting it as it should (note that this is a very naive and unverified implementation):

FILE* pInput = fopen("file.txt", "r"); 
FILE* pOutput = fopen("output.JPG","wb");

unsigned char index = 0, byte = 0;
char line[32]; // Arbitrary, few characters should be enough
while (fgets(line, sizeof(line), pInput))
{
    if (line[0] == '1')
        byte = (unsigned char)(byte | (1 << index));

    if (++index == 8)
    {
        fwrite(&byte, 1, 1, pOutput);

        index = 0;
        byte = 0;
    }
}

fclose(pInput);
fclose(pOutput);

Assumption: Each Row ( , , , 1024 , 1024 * 8 = 8192 ). , - () ( , ).

, - :

void convertToBit(void* pBuffer, size_t length)
{
    FILE* pOutput = fopen("file.txt", "w");
    for (size_t i=0; i < length; ++i)
    {
        unsigned char byte = (unsigned char)pBuffer[i];
        for (int bitIndex=0; bitIndex < 8; ++bitIndex)
        {
            if ((byte & (1 << bitIndex)) != 0)
                fputs("1\n", pOutput);
            else
                fputs("0\n", pOutput);
        }
    }

    fclose(pOutput);
}
+2

, , . jpeg - FF D8, , , , .

, imagem, - , fread()/fwrite , , / caracters? ( , , - , )

....

0

All Articles