Question

I'm trying to construct a ppm file that will give me the image of this flag:

enter image description here

It is a 1200 (columns) by 600 (rows) image and the width of the vertical red bar is 300 columns. I already wrote the code and it compiled fine, but when I try to view the ppm file in Gimp, it complains with: Premature end of file. I don't know what's happening because I constructed the ppm files for two previous flags with the exact same format (just different for loops) and those were displayed by Gimp (although I did have some trouble, I had to restart Gimp a few times).

Here's my code for this flag:

#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);
}
Was it helpful?

Solution

The final image itself still has the same height. So loop over height, and in that loop write one row of the pixels. For the red part it's simple, as it's the full height. For the other colors you have to check the current height and change color accordingly.

Something like the following (pseudo code):

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top