How to draw bitmap as OpenGL texture in C++?
I have a bitmap, and its handle (Win32 HBITMAP). Any suggestion of how to draw开发者_开发百科 this bitmap on an OpenGL quad (with scaling and pulling the 4 corners of the bitmap to fit the 4 vertexes of the quad)?
You need to retrieve the data contained in the HBITMAP, see http://msdn.microsoft.com/en-us/library/dd144879(v=vs.85).aspx Then you can upload the DIB data to OpenGL using glTexImage2D or glTexSubImage2D
With a texture being created you can apply this like usual (enable texturing, give each corner of the quad a texture coordinate).
EDIT due to comment
This (untested!) code should do the trick
GLuint load_bitmap_to_texture(
HDC device_context,
HBITMAP bitmap_handle,
bool flip_image) /* untested */
{
const int BytesPerPixel = sizeof(DWORD);
SIZE bitmap_size;
if( !GetBitmapDimensionEx(bitmap_handle, &bitmap_size) )
return 0;
ssize_t bitmap_buffer_size = bitmap_size.cx * bitmap_size.cy * BytesPerPixel;
#ifdef USE_DWORD
DWORD *bitmap_buffer;
#else
void *bitmap_buffer;
#endif
bitmap_buffer = malloc(bitmap_buffer_size);
if( !bitmap_buffer )
return 0;
BITMAPINFO bitmap_info;
memset(&bitmap_info, 0, sizeof(bitmap_info));
bitmap_info.bmiHeader.biSize = sizeof(bitmap_info.bmiHeader);
bitmap_info.bmiHeader.biWidth = bitmap_size.cx;
bitmap_info.bmiHeader.biHeight = bitmap_size.cy;
bitmap_info.bmiHeader.biPlanes = 1;
bitmap_info.bmiHeader.biBitCount = BitsPerPixel;
bitmap_info.bmiHeader.biCompression = BI_RGB;
if( flip_image ) /* this tells Windows where to set the origin (top or bottom) */
bitmap_info.bmiHeader.biHeight *= -1;
if( !GetDIBits(device_context,
bitmap_handle,
0, bitmap_size.cy,
bitmap_buffer,
&bitmap_info,
DIB_RGB_COLORS /* irrelevant, but GetDIBits expects a valid value */ )
) {
free(bitmap_buffer);
return 0;
}
GLuint texture_name;
glGenTextures(1, &texture_name);
glBindTexture(GL_TEXTURE_2D, texture_name);
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_TRUE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
bitmap_size.cx, bitmap_size.cy, 0,
GL_RGBA,
#ifdef USE_DWORD
GL_UNSIGNED_INT_8_8_8_8,
#else
GL_UNSIGNED_BYTE,
#endif
bitmap_buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
free(bitmap_buffer);
return texture_name;
}
精彩评论