Search code examples
cimage-processingbmp

Get the RGB value of each pixel from bmp file


So I have a bmp file, and I want to extract the details of rgb for every pixel of the image.

I read somewhere that the following would do this for me

int main(){
int image[100][3]; // first number here is 100 pixels in my image, 3 is for RGB     values
 FILE *streamIn;
 int i;
 streamIn = fopen("./t.bmp", "r");
 if (streamIn == (FILE *)0){
    printf("File opening error ocurred. Exiting program.\n");
    return 0;
 }

  int byte;
  int count = 0;
  for(i=0;i<54;i++) byte = getc(streamIn);  // strip out BMP header

  for(i=0;i<100;i++){    // foreach pixel
     image[i][2] = getc(streamIn);  // use BMP 24bit with no alpha channel
     image[i][1] = getc(streamIn);  // BMP uses BGR but we want RGB, grab byte-by-byte
     image[i][0] = getc(streamIn);  // reverse-order array indexing fixes RGB issue...
     //printf("[%d,%d,%d] ",image[i][0],image[i][1],image[i][2]);
     if(image[i][0]==255 && image[i][1]==255 && image[i][2]==255)
        printf("B");
     else if(image[i][0]==0 && image[i][1]==0 && image[i][2]==0)
        printf("W");
     else{
        printf("[%d,%d,%d]",image[i][0],image[i][1],image[i][2]);
        //return 0;
     }
  }

  fclose(streamIn);
  return 0;
 }

Now considering my bmp file is 10*10 pixel, will the above method work?

Edit I have added an answer, maybe that can help someone. Cheers.


Solution

  • This code sample is very crude and I wouldn't recommend doing it this way.

    However, if you insist, there's a rule you need to know about: every row is padded to an exact multiple of 4 bytes. In your case a row is 10*3 or 30 bytes, so it gets 2 extra bytes of padding. If you don't account for that as you read the file, you'll be off.