gpt4 book ai didi

c - 用C写一个JPG图片文件

转载 作者:行者123 更新时间:2023-12-04 13:15:44 26 4
gpt4 key购买 nike

我读取 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);
}

谢谢,

-山姆

最佳答案

尝试重写如下(请注意,这是一个非常幼稚且未经测试的实现):

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

假设:输入文件的每一都是原始文件的单个(这意味着如果原始文件是,例如,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);
}

关于c - 用C写一个JPG图片文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com