이재원
이재원

Reputation: 87

(Bitmap)LoadImage() returns NULL and GetLastError() returns 0

I'm trying to draw a bitmap file on window. So I used (HBITMAP)LoadImage() and it returns NULL. I used GetLastError to see the problem but it returns 0 too. I'm working on goorm ide(windows application).

    HBITMAP hBitmap = NULL;
    hBitmap = (HBITMAP)LoadImageW( NULL, L"C:\\Users\\Asd\\Downloads\\image.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE );

    if(hBitmap == NULL){
        DWORD errorCode = GetLastError();
        if(errorCode != 0){
            LPSTR messageBuffer = nullptr;
            FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                errorCode,
                0,
                (LPTSTR)&messageBuffer,
                0,
                NULL);
                MessageBox(NULL, messageBuffer, "hBitmap is NULL!" , MB_OK);
                }else{
                    MessageBox(NULL, "hBitmap is null but errorCode is 0", "???" , MB_OK);
                }
            }

If I change the "image.bmp" to "asdf.bmp" in the code, It says "there is no file." so I'm sure that It found file but seems not working right. when I print Width and Height of bitmap, It shows strange number(like 12312321, -3453453). I can't find what is problem.

I tried this too: (from https://support.microsoft.com/en-us/help/158898/howto-how-to-use-loadimage-to-read-a-bmp-file)

hBitmap = (HBITMAP)LoadImage( NULL, "image.bmp", IMAGE_BITMAP, 0, 0,
               LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE );

Upvotes: 0

Views: 3003

Answers (2)

Neuromancer1966
Neuromancer1966

Reputation: 31

Got this with BOOL LoadBitmap(UINT nIDResource) and a GIMP-created bmp. Load the resource bmp file into Paint and do some pseudo-change to convince Paint that you changed the bmp. Save the bmp. The problem has gone away! I did not drill deeper to find the root cause. LoadBitmap does not like GIMP-created bmp files.

Upvotes: 3

Strive Sun
Strive Sun

Reputation: 6289

I create the simplest Windows Desktop Application.

And only added WM_CREATE and WM_PAINT message events.

I added my own bmp image and can successfully load the image.

Like this:

hBitmap = (HBITMAP)LoadImage(GetModuleHandle(NULL), L"C:\\Users\\strives\\Desktop\\panda.bmp", IMAGE_BITMAP, 0, 0,
            LR_DEFAULTSIZE | LR_LOADFROMFILE);

From your answer in the comments, you have tried to use an absolute path to load the image, but you have not considered a problem. That's the image format, if you just changed the suffix of a JPG image to .bmp, then your hBitmap will return 0, and GetLasterror will also return 0.

So all you have to do is use a properly formatted BMP image. If there is no such image, please use the image conversion format tool to convert.

In addition, I have encountered a similar post before, you can refer.

Upvotes: 3

Related Questions