Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

c - Getting the pixel value of BMP file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
");
   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]
",i+1,image[i][0],image[i][1],image[i][2]);
 }

 fclose(streamIn);

~Locutus


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...