void CXXXDlg::SaveBitmap(CONST BYTE* pImageBuffer, int nImageSize, int nImageWidth, int nImageHeight)
{
do
{
// Set Save Bitmap Path
TCHAR szPath[MAX_PATH] = {0};
GetModuleFileName(NULL, szPath, _countof(szPath));
_tcsrchr(szPath, _T('\\'))[1] = _T('\0');
_tcscat_s(szPath, _countof(szPath) - _tcslen(szPath), _T("Barcode.bmp"));
// Create File
HANDLE hFile = CreateFile(szPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(INVALID_HANDLE_VALUE == hFile)
{
break;
}
#define DEFAULT_RGBQUAD_COUNT (256)
#define DEFAULT_BITCOUNT_BASE (8)
// Get Bitmap BitCount
int nBitCount = (nImageSize / (nImageWidth * nImageHeight)) * DEFAULT_BITCOUNT_BASE; // BitCount
// Get Bitmap Color
int nColors = 1 << nBitCount;
if(nColors > DEFAULT_RGBQUAD_COUNT) { nColors = 0; }
// Bitmap File Header
BITMAPFILEHEADER bfh = {0};
bfh.bfType = 0x4d42; // 'BM'
bfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + nColors * sizeof(RGBQUAD) + nImageSize;
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + nColors * sizeof(RGBQUAD);
WriteFile(hFile, &bfh, sizeof(BITMAPFILEHEADER), NULL, NULL); // Bitmap File Header
// Bitmap Info Header
BITMAPINFOHEADER bih = {0};
bih.biBitCount = (WORD)nBitCount;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = nImageWidth;
bih.biHeight = nImageHeight;
bih.biPlanes = 1;
bih.biCompression = BI_RGB;
bih.biSizeImage = (((bih.biWidth * bih.biBitCount + 31) & ~31) / DEFAULT_BITCOUNT_BASE) * bih.biHeight;
WriteFile(hFile, &bih, sizeof(BITMAPINFOHEADER), NULL, NULL); // Bitmap Information Header
// RGBQUAD Data
RGBQUAD rgbQuad[DEFAULT_RGBQUAD_COUNT] = {0};
for(size_t i = 0; i != _countof(rgbQuad); ++i)
{
rgbQuad[i].rgbRed = rgbQuad[i].rgbGreen = rgbQuad[i].rgbBlue = (BYTE)i;
rgbQuad[i].rgbReserved = 0;
}
WriteFile(hFile, rgbQuad, nColors * sizeof(RGBQUAD), NULL, NULL); // RGBQUAD
// Bitmap Data
WriteFile(hFile, pImageBuffer, nImageSize, NULL, NULL); // Bitmap Data
// Close File Handle
CloseHandle(hFile);
hFile = INVALID_HANDLE_VALUE;
} while (FALSE);
}