0

我正在尝试构建一个 ppm 文件,它会给我这个标志的图像:

在此处输入图像描述

它是一个 1200(列)乘 600(行)的图像,垂直红色条的宽度为 300 列。我已经编写了代码并且编译得很好,但是当我尝试在 Gimp 中查看 ppm 文件时,它会抱怨:文件过早结束。我不知道发生了什么,因为我为之前的两个标志构建了 ppm 文件,格式完全相同(只是 for 循环不同)并且 Gimp 显示了这些文件(虽然我确实遇到了一些麻烦,但我不得不重新启动 Gimp 几次)。

这是我的这个标志的代码:

#include <stdio.h>

int main() {
   printf("P6\n");
   printf("%d %d\n", 1200, 600);
   printf("255\n");

   int widthGreen, widthWhite, widthBlack, widthVertical, width, height, i, j;
   unsigned char Rcolor, Bcolor, Gcolor;

   widthGreen = 200;
   widthWhite = 400;
   widthBlack = 600;
   widthVertical = 300;
   width = 1200;
   height = 600;

   for (j = 0; j < height; j++) {
      for (i = 0; i < widthVertical ; i++) {
         Rcolor = 255;
         Gcolor = 0;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 0; j < widthGreen; j++) {
      for (i = 400; i < width; i++) {
         Rcolor = 0;
         Gcolor = 128;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 201; j <= widthWhite; j++) {
      for (i = 400; i < width; i++) {
         Rcolor = 255;
         Gcolor = 255;
         Bcolor = 255;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   for (j = 401; j <= widthBlack; j++) {
      for (i = 400; i < width; i++) {
         Rcolor = 0;
         Gcolor = 0;
         Bcolor = 0;

         printf("%c%c%c", Rcolor, Gcolor, Bcolor);
      }
   }

   return (0);
}
4

1 回答 1

1

最终图像本身仍然具有相同的高度。所以循环高度,并在该循环中写入一行像素。对于红色部分,它很简单,因为它是全高。对于其他颜色,您必须检查当前高度并相应地更改颜色。

类似于以下内容(伪代码):

for (h = 0; h < height; ++h)
{
    write_color(300, red);

    if (h < 200)
        color = green;
    else if (h < 400)
        color = white;
    else
        color = black;

    write_color(900, color);
}
于 2013-10-29T09:27:27.070 回答