Read Bmp Greyscales into C

时间秒杀一切 提交于 2020-01-24 22:09:29

问题


I looked for how to read a Bmp file into a 2 or 1 dimensional Array under C , there are many solutions but not the one i need. I need to read the Black and white bmp into (to beginn) 2 dimensional array which have to contain values from 0 to 255 (greyscale) and then transform it to 1 dimensional array(but that's not a problem). Matlab does this automticly but i want to be more autonomous working under C/C++ at the end the bmp shall be saved into a Postgre Database int array. Thanks


回答1:


There's a bmp loader which I made for another SO question:
http://nishi.dreamhosters.com/u/so_bmp_v0.zip
The example bmp there is RGB, but it seems to work with grayscale as well.

FILE* f = fopen( "winnt.bmp", "rb" ); if( f==0 ) return 1;
fread( buf, 1,sizeof(buf), f );
fclose(f);

BITMAPFILEHEADER& bfh = (BITMAPFILEHEADER&)buf[0];
BITMAPINFO& bi = (BITMAPINFO&)buf[sizeof(BITMAPFILEHEADER)];
BITMAPINFOHEADER& bih = bi.bmiHeader; 
char* bitmap = &buf[bfh.bfOffBits];
int SX=bih.biWidth, SY=bih.biHeight;

bitmap here is the pointer to the pixel table (should be made unsigned for proper access though). Note that pixel rows in bmp can be stored in reverse order.




回答2:


Sorry, misread question :/
If you don't mind "twisting" the rules a tiny little bit

#include <stdio.h>

int main(void) {
  int data[100][30] = {{0}}; /* initialize 2D array to all zeroes */
  int *p1d;
  size_t index;

  data[42][20] = 42; /* set 1 element ot 42 */
  p1d = &data[0][0];
  index = 42*30 + 20;
  printf("%d (should be 42)\n", p1d[index]); /* pretend it's a 1D array */
  return 0;
}



来源:https://stackoverflow.com/questions/5350072/read-bmp-greyscales-into-c

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