1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
HRESULT CColorBasics::SaveBitmapToFile(BYTE* pBitmapBits, LONG lWidth, LONG lHeight, WORD wBitsPerPixel, LPCWSTR lpszFilePath)
{
DWORD dwByteCount = lWidth * lHeight * (wBitsPerPixel / 8);
BITMAPINFOHEADER bmpInfoHeader = {0};
bmpInfoHeader.biSize = sizeof(BITMAPINFOHEADER); // Size of the header
bmpInfoHeader.biBitCount = wBitsPerPixel; // Bit count
bmpInfoHeader.biCompression = BI_RGB; // Standard RGB, no compression
bmpInfoHeader.biWidth = lWidth; // Width in pixels
bmpInfoHeader.biHeight = -lHeight; // Height in pixels, negative indicates it's stored right-side-up
bmpInfoHeader.biPlanes = 1; // Default
bmpInfoHeader.biSizeImage = dwByteCount; // Image size in bytes
BITMAPFILEHEADER bfh = {0};
bfh.bfType = 0x4D42; // 'M''B', indicates bitmap
bfh.bfOffBits = bmpInfoHeader.biSize + sizeof(BITMAPFILEHEADER); // Offset to the start of pixel data
bfh.bfSize = bfh.bfOffBits + bmpInfoHeader.biSizeImage; // Size of image + headers
// Create the file on disk to write to
HANDLE hFile = CreateFileW(lpszFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// Return if error opening file
if (NULL == hFile)
{
return E_ACCESSDENIED;
}
DWORD dwBytesWritten = 0;
// Write the bitmap file header
if ( !WriteFile(hFile, &bfh, sizeof(bfh), &dwBytesWritten, NULL) )
{
CloseHandle(hFile);
return E_FAIL;
}
// Write the bitmap info header
if ( !WriteFile(hFile, &bmpInfoHeader, sizeof(bmpInfoHeader), &dwBytesWritten, NULL) )
{
CloseHandle(hFile);
return E_FAIL;
}
// Write the RGB Data
if ( !WriteFile(hFile, pBitmapBits, bmpInfoHeader.biSizeImage, &dwBytesWritten, NULL) )
{
CloseHandle(hFile);
return E_FAIL;
}
// Close the file
CloseHandle(hFile);
return S_OK;
}
|