如何在 C 中正确读取 PGM 图像

How to read a PGM image properly in C

我来这里是想请你帮忙。我想编写一个 C 代码来读取 PGM 文件(P2,而不是二进制文件),并且我在 Web 上找到了很多方法。问题是每次我尝试读取我的 PC 上的一些 PGM 图像作为示例时,我什至无法正确读取 header,因为它永远无法识别正确的 P2 PGM 格式。我总是收到类似这样的错误:"not valid pgm file type" 或 "format unsupported"。这是我正在尝试的(最后一个)代码:

    #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;
    }

似乎有库可以做到这一点:来自 netpbm or PGMA_IO. If you cannot use an external library for some reason, a look at the source code may help you to figure out how the header is read. By the way, have you already had a look at the answer to this question: how-to-read-a-pgm-image-file-in-a-2d-double-array-in-c?

的 libnetpbm