C 将 PPM 图像显示为文本

标签 c file ppm

我是 C 编程新手,正在尝试文件操作,我正在尝试输出一个 PPM 文件及其注释和 RGB 数据值,如下所示:

P3
# The same image with width 3 and height 2,
# using 0 or 1 per color (red, green, blue)
3 2 1
1 0 0   0 1 0   0 0 1
1 1 0   1 1 1   0 0 0

在这个程序中,我已经能够检查它是否具有正确的格式并读入结构,但我遇到的问题是如何收集 RGB 数据然后将其打印出来。这是我到目前为止所拥有的。显示此信息的方法是我已经启动的 showPPM 结构,但不知道如何读取图像结构并收集其 rgb 值并显示它,任何帮助都会很棒。

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

typedef struct {
 unsigned char red,green,blue;
} PPMPixel;

typedef struct {
 int x, y;
 PPMPixel *data;
} PPMImage;


static PPMImage *readPPM(const char *filename)
{
     char buff[16];
     PPMImage *img;
     FILE *fp;
     int c, rgb_comp_color;
     //open PPM file for reading
     fp = fopen(filename, "rb");
     if (!fp) {
          fprintf(stderr, "Unable to open file '%s'\n", filename);
          exit(1);
     }

     //read image format
     if (!fgets(buff, sizeof(buff), fp)) {
          perror(filename);
          exit(1);
     }

//check the image format
if (buff[0] != 'P' || buff[1] != '3') {
     fprintf(stderr, "Invalid image format (must be 'P6')\n");
     exit(1);
}

//alloc memory form image
img = (PPMImage *)malloc(sizeof(PPMImage));
if (!img) {
     fprintf(stderr, "Unable to allocate memory\n");
     exit(1);
}

//check for comments
c = getc(fp);
while (c == '#') {
while (getc(fp) != '\n') ;
     c = getc(fp);
}

ungetc(c, fp);
//read image size information
if (fscanf(fp, "%d %d", &img->x, &img->y) != 2) {
     fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
     exit(1);
}

while (fgetc(fp) != '\n') ;
//memory allocation for pixel data
img->data = (PPMPixel*)malloc(img->x * img->y * sizeof(PPMPixel));

if (!img) {
     fprintf(stderr, "Unable to allocate memory\n");
     exit(1);
}

//read pixel data from file
if (fread(img->data, 3 * img->x, img->y, fp) != img->y) {
     fprintf(stderr, "Error loading image '%s'\n", filename);
     exit(1);
}

fclose(fp);
return img;
}

void showPPM(struct * image){
int rgb_array[600][400];
int i;
int j;

for(i = 0; i<600; i++)
{
    for(j = 0; j<400; j++)
    {
        printf("%d", rgb_array[i][j]);
    }
}
}


int main(){
PPMImage *image;
image = readPPM("aab.ppm");
showPPM(image);
}

最佳答案

您的代码看起来很可疑:

read PPM file and store it in an array; coded with C

对此也有一些非常好的评论和帮助。

所以,我留下下面的其他内容作为进一步的帮助:

<小时/>

这里开始有点模糊,让你有机会自己解决它......

首先,您需要将整个 ppm 文件读入缓冲区。 fread() 可能是为此选择的函数。您可以使用ftell()来获取文件的大小。接下来,您可以在 fread() 使用的缓冲区顶部对 PPMImage 结构进行类型转换,并且从那里,您应该能够通过 data 字段访问数据,如果您愿意,甚至可以使用数组表示法。 (我认为这是您现在缺少的步骤......)

一旦您可以访问数据,您应该能够根据输入数据迭代数据和 printf() 或控制台所需的任何内容。

关于C 将 PPM 图像显示为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41750380/

相关文章:

c - C语言中如何检查头文件的有效性

java - 如何高效地编写一个xml数据库文件?

c - 随机数,其范围是数组的元素

c++ - 为什么虚拟内存地址在不同的进程中是相同的?

C:读取文件而不打印同一行两次

c - Mandelbrot PPM 绘图始终为黑色

jpeg - 如何将图像从jpg格式转换为ppm(P3)

c++ - 在 C++ 中读取 PPM 图像缺少最后一个像素

c - C中putc()的宏实现

c++ - 无法理解静态行为