在C上读取二进制PGM
我正在制作一个用于读取PGM文件的库,我遇到了这个问题 我的代码无法正确读取二进制PGM图像,看起来它读取了错误的值,因此生成的图像只有“噪波” 代码非常简单:在C上读取二进制PGM,c,binary,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", &a
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
}
}
}
我做错了什么?在阅读图像时,可能存在一个问题:
pgm->data[i]=(无符号字符*)malloc(pgm->width*sizeof(无符号字符*);
fread(pgm->data[i],sizeof(unsigned char*),pgm->width,pgmfile)//逐行阅读
应该是:
pgm->data[i]=malloc(pgm->width*sizeof(unsigned char));
如果(pgm->data[i]==NULL){fprintf(stderr,“malloc失败”\n”);退出(1);}
fread(pgm->data[i],sizeof(unsigned char),pgm->width,pgmfile)//逐行阅读
实际上,
unsigned char*
是指向unsigned char的指针,sizeof(unsigned char*)
将是指针的大小(可能是8字节)。因此,将读取图像,每次读取一行时将读取8行 哇,你完全正确。该死,指针很狡猾。但即使使用此修复,它仍然不起作用,图像仍然有噪声。我会用更多的信息编辑我的帖子。好的,现在问题很容易找到。我正在打印图片上的原始魔法数字,但阅读后的信息总是以ASCII格式打印,所以它应该始终是P2。谢谢你的帮助!
typedef struct PGMImage {
char magicNumber[2];
unsigned char** data;
unsigned int width;
unsigned int height;
unsigned int maxValue;
} PGMImage;