January 12, 2012

Save BMP file using win32 API

include : windows.h
int SaveBMP ( const unsigned char *_buf, const char *_name, const int _width, const int _height )
{
 int i, j;
 BITMAPFILEHEADER bmfh;
 memset ( &bmfh, 0, sizeof ( BITMAPFILEHEADER ) );
 bmfh.bfType = 0x4d42;
 bmfh.bfSize = sizeof ( BITMAPFILEHEADER ) + sizeof ( BITMAPINFOHEADER ) + _width * _height * 3 + ( _width % 4 ) * _height + 2;
 bmfh.bfReserved1 = 0;
 bmfh.bfReserved2 = 0;
 bmfh.bfOffBits = sizeof ( BITMAPFILEHEADER ) + sizeof ( BITMAPINFOHEADER );

 BITMAPINFOHEADER bmih;
 memset ( &bmih, 0, sizeof ( BITMAPINFOHEADER ) );
 bmih.biSize = sizeof ( BITMAPINFOHEADER );
 bmih.biWidth = _width;
 bmih.biHeight = _height;
 bmih.biPlanes = 1;
 bmih.biBitCount = 24;
 bmih.biCompression = BI_RGB;
 bmih.biSizeImage = 0;
 bmih.biXPelsPerMeter = 0;
 bmih.biYPelsPerMeter = 0;
 bmih.biClrUsed = 0;
 bmih.biClrImportant = 0;

 FILE *bmf = NULL;
 if ( fopen_s ( &bmf, _name, "wcb" ) != 0 ) return -1;

 fwrite ( &bmfh, sizeof ( BITMAPFILEHEADER ), 1, bmf );
 fwrite ( &bmih, sizeof ( BITMAPINFOHEADER ), 1, bmf );

 unsigned char c = 0;
 int index;

 for ( i = _height-1; i >= 0; i-- )
 {
  for ( j = 0; j < _width; j++ )
  {
   index = i*_width+j;
   c = _buf[index*4+2];
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
   c = _buf[index*4+1];
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
   c = _buf[index*4+0];
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
  }

  c = 0;
  switch ( _width % 4 )
  {
  case 3:
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
  case 2:
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
  case 1:
   fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
  case 0:
   break;
  }
 }

 c = 0;
 fwrite ( &c, sizeof ( unsigned char ), 1, bmf );
 fwrite ( &c, sizeof ( unsigned char ), 1, bmf );

 fflush ( bmf );
 fclose ( bmf );
 bmf = NULL;

 return 1;
}

No comments:

Post a Comment