Search code examples
c++cpostgresqlbmpgrayscale

Read Bmp Greyscales into C


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


Solution

  • 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.