2016-03-04 137 views
0

我在这里要求您提供一些帮助。我想编写一个读取PGM文件(P2,不是二进制文件)的C代码,并且我已经找到了很多方法在Web上执行它。问题在于,每次我尝试阅读我PC上的一些PGM图像时,我甚至无法正确读取标题,因为它无法识别正确的P2 PGM格式。我总是得到如下错误:“无效的pgm文件类型”或“不支持的格式”。下面是我想要的(最后一个)代码:如何正确读取PGM图像C

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

    typedef struct pgm { 
     int w; 
     int h; 
     int max; 
     int* pData; 
    } pgm; 


    int main(int argc, char * argv[]){ 

     char* filename = argv[0]; 
     pgm* pPgm; 
     FILE* ifp; 
     int word; 
     int nRead = 0; 
     char readChars[256]; 

     //open the file, check if successful 
     ifp = fopen(filename, "r"); 
     if (!ifp) { 
     printf("Error: Unable to open file %s.\n\n", filename); 
     exit(1); 
     } 

     pPgm = (pgm *) malloc (sizeof(pgm)); 

     //read headers from file 
     printf ("Reading PGM file: %s...\n", filename); 
     fscanf (ifp, "%s", readChars); 

     if (strcmp(readChars, "P2") == 0) { 
     //valid file type 
     //get a word from the file 
     printf("VALID TYPE.\n"); 
     fscanf (ifp, "%s", readChars); 
     while (readChars[0] == '#') { 
      //if a comment, get the rest of the line and a new word 
      fgets (readChars, 255, ifp); 
      fscanf (ifp, "%s", readChars); 
     } 

     //ok, comments are gone 
     //get width, height, color depth 
     sscanf (readChars, "%d", &pPgm->w); 
     fscanf (ifp, "%d", &pPgm->h); 
     fscanf (ifp, "%d", &pPgm->max); 
     printf("WIDTH: %d, HEIGHT: %d\n", pPgm->w, pPgm->h); 

     // allocate some memory, note that on the HandyBoard you want to 
     // use constant memory and NOT use calloc/malloc 
     pPgm->pData = (int*)malloc(sizeof(int) * pPgm->w * pPgm->h); 

     // now read in the image data itself  
     for (nRead = 0; nRead < pPgm->w * pPgm->h; nRead++) { 
      fscanf(ifp, "%d" ,&word); 
      pPgm->pData[nRead] = word; 
      // printf("nRead = %d %d\n",nRead,pPgm->pData[nRead]); 
     } 

     printf ("Loaded PGM. Size: %dx%d, Greyscale: %d \n", 
     pPgm->w, pPgm->h, pPgm->max + 1); 
     } 
     else { 
     printf ("Error: %s. Format unsupported.\n\n", readChars); 
     exit(1); 
     } 
     fclose(ifp); 

     return 0; 
    } 
+1

也许你的PGM不正确。它应该是一个简单的ASCII文件,用选择的代码编辑器打开它,并根据[规范](http://netpbm.sourceforge.net/doc/pgm.html)进行验证。 – usr2564301

+0

请注意,他们说[你不应该在C]中输入'malloc()'的结果(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)。 – MikeCAT

+0

我打开了每一张pgm图片,所有图片看起来都是正确的。 – sibly22

回答