简体   繁体   中英

How to load ImGui image from byte array with opengl?

I am trying to render an image in my c++ ImGui menu; I believe the end code would be something like ImGui::Image(ImTextureID, ImVec2(X, Y)); . I already have a byte array that includes the image I want to render, but don't know how to go about loading it into that ImTextureID that's being passed in. I have found how to do it with Direct X using D3DXCreateTextureFromFileInMemoryEx but need to know the opengl equivalent for doing this.

The 'ImTextureID' in ImGui::Image is simply an int, with a value corresponding to a texture that has been generated in your graphics environment (DirectX or OpenGL).

A way to do so in OpenGL is as follows (I'm not familiar with DirectX but I bet that 'D3DXCreateTextureFromFileInMemoryEx' does pretty much the same):

  1. Generate the texture name (this 'name' is just an integer, and it is the integer that ImGui uses as ImTextureID) using glGenTextures()
  2. Set UV sampling parameters for the newly generated texture using glTexParameteri()
  3. Bind the texture to the currently active texture unit using glBindTexture()
  4. Upload pixel data to the GPU using glTexImage2D()

Typically that would look like something like this:

int textureID;
glGenTextures(GL_TEXTURE_2D, 1, &textureID);
glTextureParameteri(textureID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(textureID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(textureID, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTextureParameteri(textureID, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, [width of your texture], [height of your texture], false, GL_RGBA, GL_FLOAT, [pointer to first element in array of texture pixel values]);

It's been a while since I did this in c++ so I might be wrong on some details. But the documentation is pretty good, and best to read it anyway to figure out how to make a texture compatible with the type of texture data you intend to input: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml

Once setting up the texture like that, you use the value of textureID in the ImGui Image call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM