CreateDIBSection() failed - how to diagnose - c++

I have a call to CreateDIBSection() which is returning 0. The documentation says that this means that "One or more of the input parameters is invalid" but there is no indication of which parameter is invalid.
I had a look that this SO question in which the question ends with "after CreateDIBSection I found the error code is 8, no enough resource" - this confused me - there is no mention of any error codes in the documentation. How did the the poster get this extra information?
EDIT: As requested, here is my code - I must apologise it is not complete - it is part of a huge program, and making a minimal winapi program is not trivial.
HDC hdcTemp;
BYTE* bitPointer;
hdcTemp = CreateCompatibleDC(hdc_desktop);
my_printf("GetDeviceCaps(hdcTemp,BITSPIXEL) = %d\n",GetDeviceCaps(hdcTemp,BITSPIXEL)); // this prints "32"
static BITMAPINFO bitmap;
bitmap.bmiHeader.biSize = sizeof(bitmap.bmiHeader);
bitmap.bmiHeader.biWidth = 280;
bitmap.bmiHeader.biHeight = height_to_check;
bitmap.bmiHeader.biPlanes = 1;
bitmap.bmiHeader.biBitCount = 32;
bitmap.bmiHeader.biCompression = BI_RGB;
bitmap.bmiHeader.biSizeImage = 280 * 4 * height_to_check;
bitmap.bmiHeader.biClrUsed = 0;
bitmap.bmiHeader.biClrImportant = 0;
HBITMAP hBitmap2 = CreateDIBSection(hdcTemp, &bitmap, DIB_RGB_COLORS, (void**)(&bitPointer), NULL, NULL);

change to
BYTE* bitPointer;
HDC hdcScreen = GetDC(NULL);
static BITMAPINFO bitmap;
bitmap.bmiHeader.biSize = sizeof(bitmap.bmiHeader);
bitmap.bmiHeader.biWidth = 280;
bitmap.bmiHeader.biHeight = height_to_check;
bitmap.bmiHeader.biPlanes = 1;
bitmap.bmiHeader.biBitCount = 32;
bitmap.bmiHeader.biCompression = BI_RGB;
bitmap.bmiHeader.biSizeImage = 280 * 4 * height_to_check;
bitmap.bmiHeader.biClrUsed = 0;
bitmap.bmiHeader.biClrImportant = 0;
HBITMAP hBitmap2 = CreateDIBSection(hdcScreen, &bitmap, DIB_RGB_COLORS, (void**)(&bitPointer), NULL, NULL);
ReleaseDC(NULL, hdcScreen);
i.e. don't pass an HDC returned from CreateCompatibleDC to CreateDIBSection; use the device context of the screen.
Calling CreateCompatibleDC creates the device context with a 1x1 monochrome bitmap associated with it no matter what HDC you passed in so when you create a bitmap or DIB section compatible to that HDC Win32 tries to be compatible with the monochrome bitmap which you dont want.

At present, MSDN points out that "one or more input parameters are invalid" is reasonable. Tests show that if the bitmap size is too large or the input value is invalid, such as zero, NULL will be returned.

Related

retrieve window screenshot / capture

I have a remote application that the a screenshot using "windows handle". ( I mean HDC, HBITMAP, ....).
The code look like this :
int nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
int nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
HDC hDesktopDC = CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL);
HDC hCaptureDC = CreateCompatibleDC(hDesktopDC);
HBITMAP hCaptureBitmap =CreateCompatibleBitmap(
hDesktopDC,
nScreenWidth,
nScreenHeight);
SelectObject(hCaptureDC,hCaptureBitmap);
BitBlt(
hCaptureDC,
0,0,
nScreenWidth,nScreenHeight,
hDesktopDC,
0,0,
SRCCOPY);
BITMAPINFOHEADER info;
info.biSize = sizeof(BITMAPINFOHEADER);
info.biWidth = nScreenWidth;
info.biHeight = nScreenHeight;
info.biPlanes = 1;
info.biBitCount = 32;
info.biCompression = BI_RGB;
info.biSizeImage = 0;
info.biXPelsPerMeter = 0;
info.biYPelsPerMeter = 0;
info.biClrUsed = 0;
info.biClrImportant = 0;
//reteive the image data
byte *bits= (byte*)malloc(nScreenWidth*nScreenHeight*4);
GetDIBits(hDesktopDC, // handle to DC
hCaptureBitmap, // handle to bitmap
0, // first scan line to set
nScreenHeight, // number of scan lines to copy
bits, // array for bitmap bits
(BITMAPINFO*)&info, // bitmap data buffer
DIB_RGB_COLORS // RGB
);
DeleteDC(hDesktopDC);
DeleteDC(hCaptureDC);
DeleteObject(hCaptureBitmap);
After many loop the (about 2000) the CreateDC() function return NULL. And, if I old the DC (mean intialize it once, then destroyed on application exit) my application window flick (or part of it) or even get entirely invisible.
Thus, I'll need to know how to figure this issue out or know any other better way to get the screen image (bits/RGB data).

Win32 Create Bitmap from Device Context To File and/or BLOB

I would like to get the context of my window into a bitmap. I use the window to draw basic lines with touch. The problem that I'm having is my bitmap is black. Which it is probably due to the fact that I'm not grabbing the device context properly or doing something else wrong.
The functions CreateBitmapInfoStruct and CreateBMPFile are from this MSDN example.
Also note that g_hWnd is a global variable that has the handle of the window for which I want to save the picture.
My end goal is to be able to save the bitmap into a mysql field (BLOB) that I have. This is what my original problem was. Anyway, I started by first trying to create a BMP to file.
I have searched here and in other places. The best solution I found was recommended here following this MSDN example. However, it is not working.
Any help for this specific problem and/or in writing to the bitmap into a blob into mysql table, will be greatly appreciated.
Here is my code:
HDC hDC = GetDC(g_hWnd);
LPRECT rect = (LPRECT)malloc(sizeof(RECT));
GetWindowRect(g_hWnd,rect);
int h = rect->right - rect->left;
int w = rect->bottom - rect->top;
LPRECT rect = (LPRECT)malloc(sizeof(RECT));
GetWindowRect(g_hWnd,rect);
HBITMAP hBmp = CreateCompatibleBitmap(hDC,w,h);
PBITMAPINFO pbmi;
pbmi = CreateBitmapInfoStruct(g_hWnd,hBmp);
CreateBMPFile(g_hWnd, TEXT("c:\\TEMPO\\TestG2.bmp"), pbmi,
hBmp, hDC) ;
ReleaseDC(g_hWnd,hDC);
DeleteObject(hBmp);
DeleteObject(pbmi);
if (rect != nullptr)
free(rect);
EDIT:
The actual answer for capturing the screen (getDC) is to modify this sample in MSDN.
I have modified the sample here (remove the stretch) Note that still uses the goto, which I will remove.
A note about the GOTO... WHile I don't use it, I don't find it to be a problem either. I think too much has been made about the GOTO statement... like if in assembly, we wouldn't do goto (JUMPS)
Here is the code:
void saveBitmap()
{
HDC hdcScreen;
HDC hdcWindow;
HDC hdcMemDC = NULL;
HBITMAP hbmScreen = NULL;
BITMAP bmpScreen;
// Retrieve the handle to a display device context for the client
// area of the window.
hdcScreen = GetDC(NULL);
hdcWindow = GetDC(g_hWnd);
// Create a compatible DC which is used in a BitBlt from the window DC
hdcMemDC = CreateCompatibleDC(hdcWindow);
if(!hdcMemDC)
{
goto done;
}
RECT rcClient;
GetClientRect(g_hWnd, &rcClient);
hbmScreen = CreateCompatibleBitmap(hdcWindow, rcClient.right-rcClient.left,
rcClient.bottom-rcClient.top);
if(!hbmScreen)
{
goto done;
}
SelectObject(hdcMemDC,hbmScreen);
if(!BitBlt(hdcMemDC,
0,0,
rcClient.right-rcClient.left, rcClient.bottom-rcClient.top,
hdcWindow,
0,0,
SRCCOPY))
{
goto done;
}
GetObject(hbmScreen,sizeof(BITMAP),&bmpScreen);
BITMAPFILEHEADER bmfHeader;
BITMAPINFOHEADER bi;
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmpScreen.bmWidth;
bi.biHeight = bmpScreen.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 *
bmpScreen.bmHeight;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
HANDLE hDIB = GlobalAlloc(GHND,dwBmpSize);
char *lpbitmap = (char *)GlobalLock(hDIB);
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpbitmap.
GetDIBits(hdcWindow, hbmScreen, 0,
(UINT)bmpScreen.bmHeight,
lpbitmap,
(BITMAPINFO *)&bi, DIB_RGB_COLORS);
// A file is created, this is where we will save the screen capture.
HANDLE hFile = CreateFile(L"c:\\tempo\\captureqwsx.bmp",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
// Add the size of the headers to the size of the bitmap to get the total file size
DWORD dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) +
sizeof(BITMAPINFOHEADER);
//Offset to where the actual bitmap bits start.
bmfHeader.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) +
(DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bmfHeader.bfSize = dwSizeofDIB;
//bfType must always be BM for Bitmaps
bmfHeader.bfType = 0x4D42; //BM
DWORD dwBytesWritten = 0;
WriteFile(hFile, (LPSTR)&bmfHeader, sizeof(BITMAPFILEHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)&bi, sizeof(BITMAPINFOHEADER), &dwBytesWritten, NULL);
WriteFile(hFile, (LPSTR)lpbitmap, dwBmpSize, &dwBytesWritten, NULL);
//Unlock and Free the DIB from the heap
GlobalUnlock(hDIB);
GlobalFree(hDIB);
//Close the handle for the file that was created
CloseHandle(hFile);
//Clean up
done:
DeleteObject(hbmScreen);
DeleteObject(hdcMemDC);
ReleaseDC(NULL,hdcScreen);
ReleaseDC(g_hWnd,hdcWindow);
}
You can use GetDIBits().
This function copies the image pixels data into your own allocated memory.
See GetDIBits and loop through pixels using X, Y for some more details and explanation.

Reset existing HBITMAP as desktop background (Win32)

I wish to create a transparent window over the desktop.
For that purpose I've created an HDC with a background of the desktop (created HBITMAP of the desktop and applied it to my HDC), and invoked UpdateLayeredWindow.
So far, so good.
for performance issues i need to keep a persistent GDI+ object, meaning my HDC and HBITMAP need to stay the same handles between paintings (assuming the desktop DC didn't change), same as in this question.
In the first painting iteration all goes well. in the second painting iteration, since the HDC and HBITMAP haven't changed, I repaint on the existing HDC, meaning i get double images (the background is not erased).
Here's a code example of what I'm doing:
bool SomeUI::Draw()
{
BLENDFUNCTION blend = {0};
POINT ptPos = {0};
SIZE sizeWnd = {0};
POINT ptSrc = {0};
BOOL bUpdate = FALSE;
// Get the client rect
RECT rctWindow;
bool bGot = GetWindowRect(rctWindow);
if (!bGot)
return false;
// Get the desktop's device context
HDC hDCDesktop = GetDC(NULL);
if (!hDCDesktop)
return false;
int nWidth = abs(rctWindow.right - rctWindow.left);
int nHeight = abs(rctWindow.bottom - rctWindow.top);
// Create 32Bit bitmap to apply PNG transparency
VOID *ppvBits = NULL;
BITMAPINFO BitmapInfo = {0};
BitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
BitmapInfo.bmiHeader.biWidth = nWidth;
BitmapInfo.bmiHeader.biHeight = nHeight;
BitmapInfo.bmiHeader.biPlanes = 1;
BitmapInfo.bmiHeader.biBitCount = 32;
BitmapInfo.bmiHeader.biCompression = BI_RGB;
HBITMAP hBmp = CreateDIBSection(hDCDesktop, &BitmapInfo, DIB_RGB_COLORS, &ppvBits, NULL, 0);
if (!hBmp || hBmp==(HBITMAP)ERROR_INVALID_PARAMETER)
goto releaseHandles;
// Create a compatible DC and select the newly created bitmap
if (!m_hDC)
{
m_hDC = CreateCompatibleDC(hDCDesktop);
if (!m_hDC)
goto releaseHandles;
SelectObject(m_hDC, hBmp);
}
else
{
///////////////////////////////////////////////////////////////////////
//
// The problem lies here, this is where I need to reset the HBITMAP
// according to the desktop here (to have a transparent DC to work on)
//
///////////////////////////////////////////////////////////////////////
}
// The drawing logic
bool bInnerDraw = Draw(m_hDC);
if (!bInnerDraw)
goto releaseHandles;
// Call UpdateLayeredWindow
blend.BlendOp = AC_SRC_OVER;
blend.SourceConstantAlpha = 255;
blend.AlphaFormat = AC_SRC_ALPHA;
sizeWnd.cx = nWidth;
sizeWnd.cy = nHeight;
ptPos.x = rctWindow.left;
ptPos.y = rctWindow.top;
bUpdate = UpdateLayeredWindow(m_hWnd, hDCDesktop, &ptPos, &sizeWnd, m_hDC, &ptSrc, 0, &blend, ULW_ALPHA);
if (!bUpdate)
goto releaseHandles;
releaseHandles:
// releasing handles
}
Any ideas?
Found the Answer:
In order to reset the persistent HBITMAP, (reminder: it needs to stay the same handle), we'll set the desktop background of that area to a temporary HBITMAP and copy it to the persistent HBITMAP.
To achieve that (copying from one HBITMAP to the other), We'll create a temporary HDC and select the temporary HBITMAP to it, and copy the temporary HDC to the persistent HDC, usint BitBlt
Here's the code:
hBmpTemp = CreateDIBSection(hDCDesktop, &BitmapInfo, DIB_RGB_COLORS, &ppvBits, NULL, 0);
if (!hBmpTemp || hBmpTemp==(HBITMAP)ERROR_INVALID_PARAMETER)
goto releaseHandles;
HDC hTempDC = CreateCompatibleDC(NULL);
if (!hTempDC)
goto releaseHandles;
SelectObject(hTempDC, hBmpTemp);
::BitBlt(m_hPersistentDC, 0, 0, nWidth, nHeight, hTempDC, rctWindow.left, rctWindow.top, SRCCOPY);
::DeleteDC(hTempDC);

How do I create a bitmap using the BITMAPV5HEADER header?

This is my current code, but it causes an error when casting to BITMAPINFOHEADER:
/* Create the bitmap */
BITMAPINFO bmpinfo;
ZeroMemory(&bmpinfo, sizeof(bmpinfo));
BITMAPV5HEADER bmpheader;
ZeroMemory(&bmpheader, sizeof(bmpheader));
bmpheader.bV5Size = sizeof(BITMAPV5HEADER);
bmpheader.bV5Width = width;
bmpheader.bV5Height = height;
bmpheader.bV5Planes = 1;
bmpheader.bV5BitCount = 32;
bmpheader.bV5Compression = BI_BITFIELDS;
bmpheader.bV5SizeImage = width*height*4;
bmpheader.bV5RedMask = 0x00FF0000;
bmpheader.bV5GreenMask = 0x0000FF00;
bmpheader.bV5BlueMask = 0x000000FF;
bmpheader.bV5AlphaMask = 0xFF000000;
bmpheader.bV5CSType = 0x57696e20; // LCS_WINDOWS_COLOR_SPACE
bmpheader.bV5Intent = LCS_GM_BUSINESS;
bmpinfo.bmiHeader = reinterpret_cast<BITMAPINFOHEADER>(bmpheader);
void* converted = NULL;
HDC screen = GetDC(NULL);
HBITMAP result = CreateDIBSection(screen, &bmpinfo, DIB_RGB_COLORS, &converted, NULL, 0);
ReleaseDC(NULL, screen);
// Image data filled here
How will I be able to do this successfully?
BITMAPINFO isn't a true structure, it's more just documentation about how the color map follows the header. Just pass your BITMAPV5HEADER directly to CreateDIBSection:
HBITMAP result = CreateDIBSection(screen, reinterpret_cast<BITMAPINFO *>(&bmpheader), DIB_RGB_COLORS, &converted, NULL, 0);

Drawing on 8bpp grayscale bitmap (unmanaged C++)

I've been attempting to draw on an 8bpp grayscale bitmap without success. Here are some of my attempts. Maybe someone can point out what I'm doing wrong.
===================================================
Attempt 1: Create, select, and draw:
In constructor:
CBitmap bm;
bm.CreateBitmap (200, 200, 1, 8, NULL);
In OnDraw:
CDC *mdc=new CDC ();
HGDIOBJ tmp = mdc->SelectObject(bm);
Result: tmp is NULL, indicating failure.
===================================================
Attempt 2: CreateDIBSection
In constructor:
HBITMAP hbm;
BITMAPINFOHEADER bih;
BITMAPINFO bi;
HANDLE hb;
CDC* myDc = new CDC ();
HDC hdc = myDc->GetSafeHdc ();
void* bits;
RGBQUAD rq [256];
initBi ();
hbm = CreateDIBSection (hdc, &bi, DIB_RGB_COLORS, &bits, NULL, 0);
...
void CEightBitDrawingView::initBi()
{
bih.biSize = sizeof (BITMAPINFOHEADER);
bih.biWidth = 200;
bih.biHeight = -200;
bih.biPlanes = 1;
bih.biBitCount = 8;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 14173;
bih.biYPelsPerMeter = 14173;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
memset ((void *) rq, 0, 256 * sizeof (RGBQUAD));
bi.bmiHeader = bih;
bi.bmiColors = rq;
}
Result: This doesn't even compile because the BITMAPINFO bmiColors member is defined as:
RGBQUAD bmiColors[1];
so won't accept more than one RGB color. In fact, nothing I assign to this member compiles! (Could they possibly make it any more complex!?)
Any suggestions would be appreciated! Thanks!
===================================================
Here. Code that demonstrates how to - in a not managed world - allocate a dynamically sized structure on the stack, fill it in and pass it to CreateDIBSection.
#include <malloc.h>
HBITMAP CreateGreyscaleBitmap(int cx, int cy)
{
BITMAPINFO* pbmi = (BITMAPINFO*)alloca( sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)*256);
pbmi->bmiHeader.biSize = sizeof (pbmi->bmiHeader);
pbmi->bmiHeader.biWidth = cx;
pbmi->bmiHeader.biHeight = cy;
pbmi->bmiHeader.biPlanes = 1;
pbmi->bmiHeader.biBitCount = 8;
pbmi->bmiHeader.biCompression = BI_RGB;
pbmi->bmiHeader.biSizeImage = 0;
pbmi->bmiHeader.biXPelsPerMeter = 14173;
pbmi->bmiHeader.biYPelsPerMeter = 14173;
pbmi->bmiHeader.biClrUsed = 0;
pbmi->bmiHeader.biClrImportant = 0;
for(int i=0; i<256; i++)
{
pbmi->bmiColors[i].rgbRed = i;
pbmi->bmiColors[i].rgbGreen = i;
pbmi->bmiColors[i].rgbBlue = i;
pbmi->bmiColors[i].rgbReserved = 0;
}
PVOID pv;
return CreateDIBSection(NULL,pbmi,DIB_RGB_COLORS,&pv,NULL,0);
}
In both your examples, you created a new CDC with the following line:
CDC* pDC = new CDC();
But there's something missing: This will just create a new CDC object, but without a valid HDC handle attached to it. You need to call CDC::CreateCompatibleDC first, otherwise trying to select any object into this DC will fail.
Regarding the bmiColors: This member is defined as 1 sized array because the data behind it depends on the color depth and type of bitmap. This is documented in the MSDN. For example, if you had a 128x128 pixels 8Bit Bitmap, you would have to allocate the following amount of mem:
128 * 128 * sizeof(WORD) + sizeof(BITMAPINFOHEADER)
I finally resorted to using a .NET graphics tool (Aurigma) to create an 8bpp bitmap, and passed its handle to the unmanaged C++.
Then in C++:
HDC memDc = CreateCompatibleDC (NULL);
HGDIOBJ Obmp = ::SelectObject(memDc, varLayer); // Handle to 8-bit bitmap.
I was able to select the bitmap into a CDC and draw on it. Not 100% unmanaged, but this allowed me to do the drawing in unmanaged code, which gives acceptable speed.
Your bitmap needs to be compatible (same color-depth) as the display context you're going to render it on. Also, 8-bits/pixel bitmaps aren't necessarily grayscale - that's a function of what palette you're using.