Search code examples
c++winapi

(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 );

Solution

  • 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.