c - 在 C 上读取二进制 PGM

标签 c binary pgm

我正在制作一个用于读取 PGM 文件的库,但我遇到了这个问题。

我的代码无法正确读取二进制 PGM 图像,看起来它读取了错误的值,从而生成了只有“噪声”的图像

代码非常简单:

void OpenPGM(PGMImage* pgm, const char* file){
    FILE *pgmfile = fopen (file, "rb");

    fscanf (pgmfile, "%s", pgm->magicNumber);
    fscanf (pgmfile, "%d %d", &(pgm->width),&(pgm->height));
    fscanf (pgmfile, "%d", &(pgm->maxValue));

    pgm->data = malloc(pgm->height * sizeof(unsigned char*));

    if (pgm->magicNumber[1] == '2')
    {
        for (int i = 0; i < pgm->height; ++i)
        {
            pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
            for (int j = 0; j < pgm->width; ++j)            
                fscanf (pgmfile, "%d", &pgm->data[i][j]);           
        }
    } else {
        fgetc(pgmfile);// this should eat the last \n
        for (int i = 0; i < pgm->height; ++i)
        {
            pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
            fread(pgm->data[i],sizeof(unsigned char*),pgm->width,pgmfile);//reading line by line
        }
    }
}

PGMImage 看起来像这样

typedef struct PGMImage {
    char magicNumber[2];
    unsigned char** data;
    unsigned int width;
    unsigned int height;
    unsigned int maxValue;
} PGMImage;

我做错了什么?

最佳答案

阅读图片时可能会出现问题:

pgm->data[i] = (unsigned char*)malloc(pgm->width * sizeof(unsigned char*));
fread(pgm->data[i],sizeof(unsigned char*),pgm->width,pgmfile);//reading line by line

应该是:

pgm->data[i] = malloc(pgm->width * sizeof(unsigned char));
if(pgm->data[i]==NULL){fprintf(stderr,"malloc failed\n");exit(1);}
fread(pgm->data[i],sizeof(unsigned char),pgm->width,pgmfile);//reading line by line

事实上,unsigned char* 是指向 unsigned char 的指针,而 sizeof(unsigned char*) 将是指针的大小(可能是 8 个字节)。因此,读取图像时,每次读取一行时都会读取 8 行。

关于c - 在 C 上读取二进制 PGM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39672372/

相关文章:

c - 程序中的时间发生变化

c - 使用 OpenMP 和 C 的并行化功能

c++ - 两个补数的减法

java - 如何在java中写入和读取pgm p5文件

python - 在 python 中使用 cv2 读取 pgm 图像

c - R的C接口(interface)中NewEnvironment和R_NewHashedEnvironment的区别

windows - 如何自动检测并释放真正发生变化的DLL?

c - 在这个 if 条件下我要问什么?

python - Numpy 和 16 位 PGM

c - 为什么 int 存在于 C 中,为什么不只是 short 和 long