Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Save a 24 bit bitmap's pixel data to File in BMP format

0.00/5 (No votes)
24 Mar 2012 1  
This tip shows how to save a 24 bitmap to a file given filename, pixel data, bitmap width and bitmap height

Introduction

This tip is about saving a 24 bit bmp image to a file given the raw bitmap bits containing drawing data in pixels and the width and height of the image.

The code

// szPathName : Specifies the pathname
// lpBits	 : Specifies the bitmap bits
// w	: Specifies the image width
// h	: Specifies the image height

bool SaveImage(char* szPathName, void* lpBits, int w, int h)

{ 

//Create a new file for writing

FILE *pFile = fopen(szPathName, "wb");

if(pFile == NULL)

{ 

return false;

}

BITMAPINFOHEADER BMIH;

BMIH.biSize = sizeof(BITMAPINFOHEADER);

BMIH.biSizeImage = w * h * 3;

// Create the bitmap for this OpenGL context

BMIH.biSize = sizeof(BITMAPINFOHEADER);

BMIH.biWidth = w;

BMIH.biHeight = h;

BMIH.biPlanes = 1;

BMIH.biBitCount = 24;

BMIH.biCompression = BI_RGB;

BMIH.biSizeImage = w * h* 3; 

BITMAPFILEHEADER bmfh;

int nBitsOffset = sizeof(BITMAPFILEHEADER) + BMIH.biSize; 

LONG lImageSize = BMIH.biSizeImage;

LONG lFileSize = nBitsOffset + lImageSize;

bmfh.bfType = 'B'+('M'<<8);

bmfh.bfOffBits = nBitsOffset;

bmfh.bfSize = lFileSize;

bmfh.bfReserved1 = bmfh.bfReserved2 = 0;

//Write the bitmap file header

UINT nWrittenFileHeaderSize = fwrite(&bmfh, 1, 

sizeof(BITMAPFILEHEADER), pFile);

//And then the bitmap info header

UINT nWrittenInfoHeaderSize = fwrite(&BMIH, 

1, sizeof(BITMAPINFOHEADER), pFile);

//Finally, write the image data itself 

//-- the data represents our drawing

UINT nWrittenDIBDataSize = 

fwrite(lpBits, 1, lImageSize, pFile);

fclose(pFile);

 

return true;



}

History

Tip uploaded : 16th March, 2012

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here