2013-07-24 128 views
0

我正在使用文件pgm.cpgm.h來讀取PGM圖像文件,然後我的程序將操縱文件(灰度,旋轉等)。在C中讀取PGM圖像(沒有正確讀取文件)

但是,我不能得到的文件正確讀取。當我使用:

PGMImage* img = (PGMImage*)malloc(sizeof(PGMImage)); 
    char iName1[256]; 
    printf("Enter the filename of your PGM image:\n"); 
    scanf("%s", iName1); 
    getPGMfile(iName1, &img); 

控制檯返回圖像的類型,寬度,高度和最大值。但是,寬度永遠不會正確。無論我使用的是我在網上找到的.pgm文件還是我自己創建的一個.pgm文件,它通常都是0(而且它是56的一次)。我甚至試圖對圖像的寬度進行硬編碼,但即使如此,它也會導致程序崩潰。寬度應在pgm.c被讀取時,getPGMfile作用下:

void getPGMfile (char filename[], PGMImage *img) 
{ 
    FILE *in_file; 
    char ch; 
    int row, col, type; 
    int ch_int; 

    in_file = fopen(filename, "r"); 
    if (in_file == NULL) 
    { 
    fprintf(stderr, "Error: Unable to open file %s\n\n", filename); 
    exit(8); 
    } 

    printf("\nReading image file: %s\n", filename); 

    /*determine pgm image type (only type three can be used)*/ 
    ch = getc(in_file); 
    if(ch != 'P') 
    { 
     printf("ERROR(1): Not valid pgm/ppm file type\n"); 
     exit(1); 
    } 
    ch = getc(in_file); 
    /*convert the one digit integer currently represented as a character to 
    an integer(48 == '0')*/ 
    type = ch - 48; 
    printf("Type: %d", type); 
    if((type != 2) && (type != 3) && (type != 5) && (type != 6)) 
    { 
     printf("ERROR(2): Not valid pgm/ppm file type\n"); 
     exit(1); 
    } 

    while(getc(in_file) != '\n');    /* skip to end of line*/ 

    while (getc(in_file) == '#')    /* skip comment lines */ 
    { 
    while (getc(in_file) != '\n');   /* skip to end of comment line */ 
    } 

    /*there seems to be a difference between color and b/w. This line is needed 
    by b/w but doesn't effect color reading...*/ 
    fseek(in_file, -1, SEEK_CUR);    /* backup one character*/ 

    fscanf(in_file,"%d", &((*img).width)); 
    fscanf(in_file,"%d", &((*img).height)); 
    fscanf(in_file,"%d", &((*img).maxVal)); 

    //I omitted the rest, but it can be seen in the link above 

我不知道是什麼導致了這些錯誤。我在Windows 7(64位)上使用Eclipse和MinGW GCC。我的導師不能幫我解決這個問題,所以我希望你能! :)

總結:在PGM圖像的寬度總是讀錯,任何與該文件進行事後導致可執行停止工作。對寬度進行硬編碼還會導致可執行文件停止工作。

+3

getpgm不應該通過指針的地址,而是隻是根據頭文件指針:getPGMfile(iName1,IMG) – Magn3s1um

+0

你是不允許使用的NetPBM的http://netpbm.sourceforge.net/doc/libnetpbm.html –

+1

@ Magn3s1um提供的函數調用:+1,除非它是正確的答案。 – rici

回答

0

的PGM格式都按

P5 
wid ht 
xxx xxx xxx xxx 

其中xxx是柵格值。你需要閱讀寬度之前擺脫每個getc功能,或當它無法找到你正在尋找的字符執行ungetc。然後,寬度將被適當地讀取。

+0

Downvoter,請解釋。 – unxnut

+0

謝謝。這真的有幫助。我有寬度! – James

2

getpgm不應該傳遞指針的地址,但根據頭文件,而只是指針:getPGMfile(iName1,IMG)

+0

謝謝!這有幫助。任何想法爲什麼寬度不會被正確讀取? – James

+0

我可以告訴你,如果你顯示什麼是印刷可能 – Magn3s1um

+0

代碼: 'code'printf( 「\ n寬度=%d」,(* IMG).WIDTH); 'code'printf(「\ n height =%d」,(* img).height); 'code'printf( 「\ n MAXVAL =%d」,(*張圖片).maxVal); 'code'printf(「\ n」); 控制檯: 讀取圖像的文件:C:\\ balloons.pgm 類型:2 寬度= 0 高度= 480 MAXVAL = 255 – James