Save the image from window buffer
-
Hello Experts! There is a certain window, about which we know hDC & hWnd. By the window is used function SwapBuffer(hDC). I understand that the double buffer, and that buffer contains a certain image that is drawn in the window. Question! Is it possible in any way to copy the contents of the buffer to a compatible Bitmap or Image for Saving it into graphic file format? ? Regards, Onic777 onic@inbox.ru
-
Hello Experts! There is a certain window, about which we know hDC & hWnd. By the window is used function SwapBuffer(hDC). I understand that the double buffer, and that buffer contains a certain image that is drawn in the window. Question! Is it possible in any way to copy the contents of the buffer to a compatible Bitmap or Image for Saving it into graphic file format? ? Regards, Onic777 onic@inbox.ru
That is all you need .. you can then get the window size
RECT r;
GetWindowRect(hWnd, &r);
int Wth = r.right - r.left;
int Ht = r.bottom - r.top;You also have the wonderful function CreateDIBSection which just needs a DC CreateDIBSection function (Windows)[^] You will need to allocate memory to hold the bits. That size is slightly tricky it depends on what color depth you are going to ask for in bits. Typically you want RGB24 or RGB32 and the size also needs to be aligned to a 4 byte boundary. Anyhow long story short its a funny maths calc and we need to setup a bitmap header info for the call ... Lets do 24 bit colour.
BITMAPINFOHEADER BMIH;
BMIH.biSize = sizeof(BITMAPINFOHEADER);
BMIH.biBitCount = 24;
BMIH.biPlanes = 1;
BMIH.biCompression = BI_RGB;
BMIH.biWidth = Wth;
BMIH.biHeight = Ht;
BMIH.biSizeImage = ((((BMIH.biWidth * BMIH.biBitCount)+ 31) & ~31) >> 3) * BMIH.biHeight;See that funny calc at end well BMIH.biSizeImage now has the memory size you need to allocate. So allocate it and then call CreateDIBSection
char* myBits = malloc(BMIH.biSizeImage);
CreateDIBSection(hDC, (CONST BITMAPINFO*)&BMIH, DIB_RGB_COLORS, (void**)&myBits, NULL, 0);myBits now has all your image data from the DC now all you need to do is save it!!!! For a BMP file that is trivial
FILE *pFile = fopen( /* some Name */, "wb");
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 bitmap file header
UINT nWrittenFileHeaderSize = fwrite(&bmfh, 1, sizeof(BITMAPFILEHEADER), pFile);
// Write bitmap info header
UINT nWrittenInfoHeaderSize = fwrite(&BMIH, 1, sizeof(BITMAPINFOHEADER), pFile);
// Write our data we got back
UINT nWrittenDIBDataSize = fwrite(myBits, 1, lImageSize, pFile);
// Close the file
fclose(pFile);Now don't forget to free myBits when you are done that is alot of memory to bleed if you forget :-)
In vino veritas