Why is my image from my ppm file a little off?

你。 提交于 2019-12-08 06:52:54

问题


The task is to create an image of the russian flag on an image with 800 columns and 600 rows. So, the flag is divided into three equal sections (white on top, blue in the middle, and red on the bottom)

Here's my code:

#include <stdio.h>

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

   int width, heightWhite, heightBlue, heightRed, i, j;
   unsigned char Rcolor, Bcolor, Gcolor;

   width = 800;
   heightWhite = 200;
   heightBlue = 400;
   heightRed = 600;

   for (j = 0; j <= heightWhite; j++) {
      for (i = 0; i <= width; i++) {
         Rcolor = 255;
         Bcolor = 255;
         Gcolor = 255;

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

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

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

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

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

   return (0);
}

But when I looked at the image generated by my program, I noticed that the top of the blue and red bars aren't completely horizontal (it looks like part of the row that makes the top of the blue and red bar are higher up than the preceding pixels) I can't figure out why I'm getting this. I already ran my instructor's ppm file on Gimp (which is what I use to view ppm files) and the lines ARE supposed to be perfectly level. Any ideas?

(I'm not sure how to attach my ppm file, but here's what it's supposed to look like: http://users.csc.calpoly.edu/~dekhtyar/101-Fall2013/labs/lab7.html) (It's the very first flag)


回答1:


You are printing one more pixel for each row (the last row of each color prints 200 pixels more).

Change

for (i = 0; i <= width; i++) {

to

for (i = 0; i < width; i++) {

EDIT:

but how come I can say "<=" for the height?

for (j = 0; j < heightWhite; j++)  = 0...199 = 200 items
for (j = 1; j <= heightWhite; j++) = 1...200 = 200 items

Note that all your code can be executed with two loops:

#include <stdio.h>

int main(void)
{
   int width = 800, height = 600, icolor = 0, i, j;
   unsigned char color[][3] = {
      {255, 255, 255}, /* white */
      {0, 0, 255},     /* blue */
      {255, 0, 0}      /* red */
   };

   printf("P6\n");
   printf("%d %d\n", width, height);
   printf("255\n");

   for (i = 0; i < height; i++) {
      for (j = 0; j < width; j++) {
         printf("%c%c%c", color[icolor][0], color[icolor][1], color[icolor][2]);
      }
      if (i && (i % 200 == 0)) icolor++; /* 200, 400, 600 */
   }
   return 0;
}


来源:https://stackoverflow.com/questions/19651249/why-is-my-image-from-my-ppm-file-a-little-off

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!