如何在文本文件中打印24位彩色bmp图像的RGB颜色像素值?

时间:2015-11-12 10:18:40

标签: c colors bmp

我正在尝试在图像中为R,G和B打印单独的文本文件。

这是我的代码:

void main () {
  int pix_x=300,pix_y=300;    // image dimns in pixels
  int image[pix_x][pix_y][3]; // first [] number here is total pixels of each color in
                              // my image, 3 is for //RGB values
  FILE *streamIn;
  FILE *num_img_r,*num_img_g,*num_img_b;//separate files for R,G and B components

  //opening 24bit image
  streamIn = fopen("starcolor.bmp", "r"); // a bigger star in black and a smaller
                                          // star in blue (refer figure attached)
  num_img_r= fopen("redpixels.txt","w");
  num_img_g= fopen("greenpixels.txt","w");
  num_img_b= fopen("bluepixels.txt","w");

  int byte;
  int i,j;
  for(i=0;i<54;i++) {
    byte = fgetc(streamIn);  // strip out BMP header-> for //24bit bmp image
  }

  // initiating with new "i" different from above

  for(i=0;i<pix_y;i++) {
    for(j=0;j<pix_x;j++) {
      image[i][j][2] = fgetc(streamIn);  // use BMP 24bit with no alpha channel
      image[i][j][1] = fgetc(streamIn);  // BMP uses BGR but we want RGB, grab //byte-by-byte
      image[i][j][0] = fgetc(streamIn);  // reverse-order array indexing fixes //RGB issue...
      // printing R, G and B components separately in a .txt format
      if ((j+1)==pix_x) {
        // incorporating nextline ('\n') to ensure alignment for edge pixels
        fprintf(num_img_r,"%d \n",image[i][j][0]); // print R component
        fprintf(num_img_g,"%d \n",image[i][j][1]); // print G component
        fprintf(num_img_b,"%d \n",image[i][j][2]); // print B component
      }
      else {
        // for inner pixels, nextline(\n) not required
        fprintf(num_img_r,"%d ",image[i][j][0]); // R component
        fprintf(num_img_g,"%d ",image[i][j][1]); // G component
        fprintf(num_img_b,"%d ",image[i][j][2]); // B component
      }
    }
  }
}

实际图片:彩色和黑色星星:

Actual image:with colored and black star

屏幕截图:在0和背景中的星形(实际为黑色)和背景为255(注意:此处没有彩色星的痕迹!)通过在excel缩小表中打开文本文件获得

Screenshot: star shape(actually black) in 0's and background as 255(Note: No traces of colored star in this!) obtained by opening text file in excel-zoomed out table

如何在文本文件中打印颜色信息,即在文本文件中打印蓝色星?任何人都可以追踪我在阅读bmp图片时所犯的错误吗?

参考:Getting the pixel value of BMP file

0 个答案:

没有答案