gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:11:55 25 4
gpt4 key购买 nike

我的程序旨在读取和显示 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;
}
}
}
}

抱歉,我不知道如何将输出文本更改为纯文本。

最佳答案

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

void showPPM(struct PPM * image);

并且您正在传递一个FILE *:

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

关于c - PPM 图像格式,高度和宽度不显示 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com