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.biHeight = m_pData->height * -1;
pbmInfo->bmiHeader.biPlanes = 1;
pbmInfo->bmiHeader.biBitCount = m_pData->bitdepth;
pbmInfo->bmiHeader.biSizeImage = m_pData->size;
pbmInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmInfo->bmiHeader.biClrUsed = 0;
pbmInfo->bmiHeader.biClrImportant = 0;
pbmInfo->bmiHeader.biCompression = 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.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(&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);
by: Mercurius0Posted on 2005-05-19 at 13:11:20ID: 14040061
With the line: pbmInfo->bmiHeader.biHeigh t = m_pData->height * -1;
you define the height of the bitmap as a negative number.
That's why Paint gives an error.
Bitmap data is always saved "bottom up". So you should reverse the buffer before writing it to the file.