c++winapiopenglbitmaphbitmap

Loading and Converting a HBITMAP to an OpenGL Texture


I want to load a HBITMAP from a resource file and use it as an OpenGL texture. The code I use:

HBITMAP hBmp = (HBITMAP) LoadImage(hInstance, 
            MAKEINTRESOURCE(id), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
BITMAP BM;
GetObject(hBmp, sizeof(BM), &BM);

glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
GLvoid* bits = BM.bmBits;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, BM.bmWidth,
        BM.bmHeight, 0, GL_BGRA_EXT,
        GL_UNSIGNED_BYTE,
        bits);

But I allways get an error from Visual Studio that I dont have access to the pointer bits. The error is at the last line of code:

bits);

I actually can use the NULL pointer instead of bits without getting an error. I can output bits to using a messagebox. Does anybody have an idea what is wrong with my code?


Solution

  • From the GetObject documentation:

    If hgdiobj is a handle to a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.

    In context, "other means" is anything other than CreateDIBSection. You're not using CreateDIBSection, you're using LoadImage. Which category the LR_CREATEDIBSECTION flag puts you into is unclear, but the workaround is clear: Use GetDIBits.