Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the pixel value of BMP file

Tags:

c

pixel

bmp

i got a question for reading an bmp image. How can i get the pixel value(R, G, B values) in an bmp image? Can anyone help me using the C programming language?

like image 953
user239468 Avatar asked Dec 28 '09 08:12

user239468


People also ask

How is a pixel stored in BMP file?

The pixel values are stored in each bit, with the first (left-most) pixel in the most-significant bit of the first byte. Each bit is an index into a table of 2 colors. An unset bit will refer to the first color table entry, and a set bit will refer to the last (second) color table entry.

Does BMP have metadata?

Metadata allows you to view and edit BMP metadata with a few clicks.


2 Answers

Note: you may need to grab an extra byte for the alpha values if your BMP has alpha channel. In that case image would be image[pixelcount][4], and you would add another getc(streamIn) line to hold that fourth index. My BMP turned out to not need that.

 // super-simplified BMP read algorithm to pull out RGB data
 // read image for coloring scheme
 int image[1024][3]; // first number here is 1024 pixels in my image, 3 is for RGB values
 FILE *streamIn;
 streamIn = fopen("./mybitmap.bmp", "r");
 if (streamIn == (FILE *)0){
   printf("File opening error ocurred. Exiting program.\n");
   exit(0);
 }

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

 for(i=0;i<1024;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("pixel %d : [%d,%d,%d]\n",i+1,image[i][0],image[i][1],image[i][2]);
 }

 fclose(streamIn);

~Locutus

like image 114
Anon Avatar answered Sep 20 '22 17:09

Anon


The easy way would be to find a good image manipulation library for your chosen platform and use that.

  • Linux ImLib / GDK-Pixbuf (Gnome/GTK) / QT Image (KDE/Qt) should be able to do what you need.
  • Windows I'm not familiar with the appropriate system library, but an MSDN Search for "Bitmap" is probably a good place to start.
  • Mac OSX Cocoa has some image manipulation capabilities, see this article.

The hard way would be to open the file and actually interpret the binary data within. To do that you'll need the BMP File Specification. I'd recommend trying the easy way first.

like image 23
Adam Luchjenbroers Avatar answered Sep 18 '22 17:09

Adam Luchjenbroers