I'm using the following code to save a buffer to a BMP file (the buffer and size info are in m_pData, and are all set properly). The saved images looks just fine except that it is flipped upside down. So I tried making the biHeight variable negative by multiplying the height by -1 (as is shown below). The problem then is that the saved image, when I try to open it with Paint, I see a message "bitmaps must be greater than one pixel on a side" - then I click OK and Paint opens, the image is the appropriate dimensions, but all white.
Any ideas? It's an 24bit color image of 1000x1000. (the code is also intended to work with 8bit grayscale images, in which case the data in m_pData reflects 8bits and a size of 1000x1000 rather than 24 bits and 1000x1000x3)
-------------------
BITMAP bm = {0};
BITMAPINFO* pbmInfo = new BITMAPINFO;
ZeroMemory( pbmInfo, sizeof(*pbmInfo) );
pbmInfo->bmiHeader.biWidth
= m_pData->width;
pbmInfo->bmiHeader.biHeigh
t = m_pData->height * -1;
pbmInfo->bmiHeader.biPlane
s = 1;
pbmInfo->bmiHeader.biBitCo
unt = m_pData->bitdepth;
pbmInfo->bmiHeader.biSizeI
mage = m_pData->size;
pbmInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmInfo->bmiHeader.biClrUs
ed = 0;
pbmInfo->bmiHeader.biClrIm
portant = 0;
pbmInfo->bmiHeader.biCompr
ession = BI_RGB;
void *buffer = NULL;
HBITMAP hBmp = ::CreateDIBSection(0, pbmInfo, DIB_RGB_COLORS, &buffer, NULL, 0);
if (!hBmp)
return false;
// Copy the image into the buffer.
FILE *pFile = fopen(sPath, "wb");
if(pFile == NULL)
return FALSE;
BITMAPFILEHEADER bmfh;
int nBitsOffset = sizeof(BITMAPFILEHEADER) + pbmInfo->bmiHeader.biSize;
LONG lImageSize = pbmInfo->bmiHeader.biSizeI
mage;
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(&pbmInfo->bmiHeader
, 1, sizeof(BITMAPINFOHEADER), pFile);
//Finally, write the image data itself
//-- the data represents our drawing
UINT nWrittenDIBDataSize = fwrite(m_pData->buffer, 1, lImageSize, pFile);
fclose(pFile);