Skip to content

Instantly share code, notes, and snippets.

@mazhar-ansari-ardeh
Last active November 9, 2016 10:39
Show Gist options
  • Save mazhar-ansari-ardeh/29ec82ab3a5cdc8b7c2183e9ef612402 to your computer and use it in GitHub Desktop.
Save mazhar-ansari-ardeh/29ec82ab3a5cdc8b7c2183e9ef612402 to your computer and use it in GitHub Desktop.
The 'GetBits' function retrieves the bytes of a given HBITMAP handle. The same functionality is usually achieved with the 'GetDIBits' method of GDI. Windows CE does not support the 'GetDIBits' method. The 'GetBits' method can be improved.
#include <windows.h>
HBITMAP WINAPI GetBits(HBITMAP h, LONG width, LONG height, WORD bitCount, BYTE **bytes, DWORD *bytesLen)
{
// Sanity check omitted.
HDC hdcScreen;
hdcScreen = GetDC(NULL);
if (hdcScreen == NULL)
{
*bytes = NULL;
*bytesLen = 0;
return NULL;
}
HDC hdcMemoryDCOfFileBitmap;
hdcMemoryDCOfFileBitmap = CreateCompatibleDC(hdcScreen);
if (hdcMemoryDCOfFileBitmap == NULL) {
DeleteDC(hdcScreen);
*bytes = NULL;
*bytesLen = 0;
return 0;
}
SelectObject(hdcMemoryDCOfFileBitmap, h);
HDC hdcMemoryDCOfDIBSection;
hdcMemoryDCOfDIBSection = CreateCompatibleDC(hdcScreen);
if (hdcMemoryDCOfDIBSection == NULL) {
DeleteDC(hdcScreen);
DeleteDC(hdcMemoryDCOfFileBitmap);
*bytes = NULL;
*bytesLen = 0;
return NULL;
}
BITMAPINFO bmi;
ZeroMemory(&bmi, sizeof bmi);
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = (-1) * height;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = bitCount;
bmi.bmiHeader.biCompression = BI_RGB;
DWORD bytes_per_scanLine = ((((bmi.bmiHeader.biWidth * bmi.bmiHeader.biBitCount) + 31) / 32) * 4);
//LONG pad_per_scanLine = bytes_per_scanLine - (((m_BitInfo.bmiHeader.biWidth * m_BitInfo.bmiHeader.biBitCount) + 7) / 8);
bmi.bmiHeader.biSizeImage = bytes_per_scanLine * abs(bmi.bmiHeader.biHeight);
BYTE *pixelBuffer;
HBITMAP hbmp;
hbmp = CreateDIBSection(hdcScreen, &bmi, DIB_RGB_COLORS, reinterpret_cast<void **>(&pixelBuffer), NULL, 0);
if (hbmp == NULL) {
DeleteDC(hdcScreen);
DeleteDC(hdcMemoryDCOfFileBitmap);
DeleteDC(hdcMemoryDCOfDIBSection);
*bytes = NULL;
*bytesLen = 0;
return NULL;
}
HBITMAP oldBmp;
oldBmp = HBITMAP(SelectObject(hdcMemoryDCOfDIBSection, hbmp));
if (oldBmp == NULL) {
DeleteDC(hdcScreen);
DeleteDC(hdcMemoryDCOfFileBitmap);
DeleteDC(hdcMemoryDCOfDIBSection);
DeleteObject(hbmp);
*bytes = NULL;
*bytesLen = 0;
return NULL;
}
BOOL success = BitBlt(hdcMemoryDCOfDIBSection, 0, 0, width, height, hdcMemoryDCOfFileBitmap, 0, 0, SRCCOPY);
if(FALSE != success)
{
*bytes = reinterpret_cast<BYTE*>( *pixelBuffer);
*bytesLen = bmi.bmiHeader.biSizeImage;
}
else
{
*bytes = NULL;
*bytesLen = 0;
DeleteObject(hbmp);
hbmp = NULL;
}
DeleteDC(hdcScreen);
DeleteDC(hdcMemoryDCOfFileBitmap);
DeleteDC(hdcMemoryDCOfFileBitmap);
DeleteDC(hdcMemoryDCOfDIBSection);
return hbmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment