PPM图像格式,高度和宽度不显示 - C.

时间:2016-02-11 23:30:42

标签: c image format

我的用于读取和显示PPM图像的程序不会打印正在读取的图像的实际格式或高度或宽度。这可能是一个非常基本的错误,但我很长时间没有使用过C语言。

编辑:我实际上只是注意到我检查图像格式的有效位置,我检查它是否= = 2,但它应该是!= 2(如果我是我的话,请更正我错误)所以它说我的图像格式无论如何都是无效的。我会尝试在另一张图片上运行我的代码。

如果有人能提供帮助那就太棒了。

当前输出:

PPM FILE PROGRAM
Memory allocation successful
File format is correct
89~
Image size: 3680602 544108293

期望的输出:

PPM FILE PROGRAM
Memory allocation successful
File format is correct
P3
Image size: 125 100

代码:

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

#define MAX_HEIGHT 600
#define MAX_WIDTH 400

struct PPM {
    char format[3]; //PPM format code
    int height, width; //image pixel height and width
    int max; //max rgb colour value
};


struct PPM_Pixel {
    //Create variables to hold the rgb pixel values
    int red;
    int green;
    int blue;
};


struct PPM *getPPM(FILE * file);
void showPPM(struct PPM * image);

int main( void ){

    printf("PPM FILE PROGRAM \n");
    FILE *file;
    // get image file
    // FILE *file;
    file = fopen("aab(1).ppm", "r");
    //if there is no file then return an error
    if(file == NULL){
        fprintf(stderr, "File does not exist\n");
        return 0;
    }

    struct PPM *newPPM = getPPM(file);
    showPPM(file);
    fclose(file);
}


struct PPM *getPPM(FILE * file){

    char buffer[3];
    int c;

    struct PPM *image = NULL;
    if(NULL == (image = malloc(sizeof(struct PPM)))){
        perror("memory allocation for PPM file failed\n");
        exit(1);
    }
    else {
        printf("Memory allocation succesful\n");
    }

    //read the image of the format
    if(!fgets(buffer, sizeof(buffer), file)){
        exit(1);
    }

    //checks the format of the ppm file is correct
    if(buffer[0] != 'P' || buffer[1] != '3'){
        fprintf(stderr, "Invalid image format! \n");
        exit(1);
    }else{
        printf("File format is correct\n");
        printf("%s\n", image->format);
    }

    //checks whether the next character is a comment and skips it
    c = getc(file);
    while(c == '#'){
        while(getc(file) != '\n'){
        c = getc(file);
        }
    }

    //check the image size is valid
    if(fscanf(file, "%d %d", &image->height, &image->width) == 2){
        printf("Invalid imaze size\n");
        exit(1);
    }else{
        printf("Image size: %d %d ", image->height, image->width);
    }

    return image;
}

void showPPM(struct PPM * image){

    struct PPM_Pixel rgb_array[MAX_HEIGHT][MAX_WIDTH];
    int i;
    int j;

    for(i = 0; i<MAX_HEIGHT; i++){
        for(j = 0; j<MAX_WIDTH; j++){
            struct PPM_Pixel newPPM_Pixel;
            if(fscanf(image, "%d %d %d", &newPPM_Pixel.red, &newPPM_Pixel.green, &newPPM_Pixel.blue) == 3){
                rgb_array[i][j] = newPPM_Pixel;
            }
        }
    }
}

道歉,我不确定如何将输出文本更改为文本。

1 个答案:

答案 0 :(得分:1)

虽然您忘记包含showPPM()的代码,但他的原型是

void showPPM(struct PPM * image);

您正在传递FILE *

FILE *file;
...
showPPM(file);