再现 RAW 图像 - C

Reproduce RAW Image - C

我正在尝试使用我用 C 编写的小程序重现一个 .raw 图像文件,但每次我 运行 我的程序都变得不可读。

我的程序所做的就是获取每个像素并将其写入相应的输出文件。

另请注意,此程序仅支持灰度图像。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fin, *fout;
    char path_in[64], path_out[64], *rev, px;
    int width, height, read, row, i;

    printf("Input file name: ");
    scanf("%s", path_in);
    printf("Output file name: ");
    scanf("%s", path_out);

    printf("Width of image (in pixels): ");
    scanf("%d", &width);
    printf("Height of image (in pixels): ");
    scanf("%d", &height);

    fin = fopen(path_in, "r");
    fout = fopen(path_out, "w");

    row = 0;
    rev = (char *)malloc(width * sizeof(char));
    while(row < height)
    {
        for(i = 0; i < width; i++)
        {
            read = fread(&px, sizeof(char), 1, fin);
            rev[i] = (unsigned int)px;
        }

        for(i = 0; i < width; i++)
            if(i < width && row < height)
                fwrite(&rev[i], sizeof(char), 1, fout);

        row++;
    }

    fclose(fout);
    fclose(fin);

    return 0;
}

它可能还有一些其他问题,但您已告诉 fopen 以文本模式打开文件:

fin = fopen(path_in, "r");
fout = fopen(path_out, "w");

而不是二进制模式:

fin = fopen(path_in, "rb");
fout = fopen(path_out, "wb");

哪个适合图像数据。

您还在进行奇怪的转换,这可能会破坏您的数据:

char ..., *rev, px;
...
rev = (char *)malloc(width * sizeof(char));
...
rev[i] = (unsigned int)px;

(unsigned int) 转换充其量是不必要的。