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.
CodePudding user response:
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):
- Generate the texture name (this 'name' is just an integer, and it is the integer that ImGui uses as ImTextureID) using glGenTextures()
- Set UV sampling parameters for the newly generated texture using glTexParameteri()
- Bind the texture to the currently active texture unit using glBindTexture()
- 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.