I need to load a bmp image from file and load image data into buffer and then create new image from it. (I have a reason for doing this way). I wrote a sample program to mimic my project scenario.
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
static BITMAP bm;
static HBITMAP bmpSource = NULL;
static HBITMAP hbmp=NULL;
static HDC hdcSource = NULL;
static HDC hdcDestination= NULL;
static PAINTSTRUCT ps;
BITMAPINFO bitmap_info[2] = {0};
if (Msg == WM_CREATE) {
bmpSource = (HBITMAP)LoadImage(NULL, L"bmp00004.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );
GetObject(bmpSource, sizeof(BITMAP), &bm);
bitmap_info->bmiHeader.biSize = sizeof(bitmap_info->bmiHeader);
int ret = GetDIBits(hdcSource, bmpSource, 0, bm.bmHeight, NULL, bitmap_info,DIB_RGB_COLORS);
LPVOID *lpvBits = (LPVOID*) malloc(3*(bm.bmWidth * bm.bmHeight * sizeof(DWORD)));
int gotData = GetDIBits(hdcSource, bmpSource, 0,bm.bmHeight,lpvBits, bitmap_info, DIB_RGB_COLORS);
hbmp = (HBITMAP) CreateBitmap(bm.bmWidth, bm.bmHeight, bm.bmPlanes, bm.bmBitsPixel ,lpvBits);
hdcSource = CreateCompatibleDC(GetDC(0));
SelectObject(hdcSource, hbmp);
return 0;
}else if (Msg == WM_PAINT) {
hdcDestination = BeginPaint(hWnd, &ps);
BitBlt(hdcDestination, 0, 0,bm.bmWidth , bm.bmHeight, hdcSource, 0, 0, SRCCOPY);
EndPaint(hWnd, &ps);
return 0;
}else if (Msg == WM_DESTROY) {
DeleteDC(hdcSource);
EndPaint(hWnd, &ps);
DeleteObject(bmpSource);
DeleteObject(hbmp);
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
I am expecting program to print the image on the window. Now the newly created image is not displayed on window. All I can see is a gray box.
Your code can be considerably simplified. There is no need to call GetDIBits
(which you are doing before you set up hdcSource
anyway), and you should clean up properly and minimise the use of static variables. Something like the following (error checking omitted for clarity):
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
static HBITMAP bmpSource;
if (Msg == WM_CREATE) {
bmpSource = (HBITMAP)LoadImage(NULL, L"bmp00004.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );
return 0;
}
if (Msg == WM_PAINT) {
PAINTSTRUCT ps;
HDC hdcDestination = BeginPaint(hWnd, &ps);
BITMAP bm;
GetObject(bmpSource, sizeof(bm), &bm);
HDC hdcSource = CreateCompatibleDC(hdcDestination);
HGDIOBJ hOldBmp = SelectObject(hdcSource, bmpSource);
BitBlt(hdcDestination, 0, 0,bm.bmWidth , bm.bmHeight, hdcSource, 0, 0, SRCCOPY);
SelectObject(hdcSource, hOldBmp);
DeleteDC(hdcSource);
EndPaint(hWnd, &ps);
return 0;
}
if (Msg == WM_DESTROY)
DeleteObject(bmpSource);
return DefWindowProc(hWnd, Msg, wParam, lParam);
}