Opengl ES 2.0 : Get texture size and other info

2019-02-18 03:39发布

问题:

The context of the question is OpenGL ES 2.0 in the Android environment. I have a texture. No problem to display or use it.

Is there a method to know its width and height and other info (like internal format) simply starting from its binding id?

I need to save texture to bitmap without knowing the texture size.

回答1:

Not in ES 2.0. It's actually kind of surprising that the functionality is not there. You can get the size of a renderbuffer, but not the size of a texture, which seems inconsistent.

The only thing available are the values you can get with glGetTexParameteriv(), which are the FILTER and WRAP parameters for the texture.

It's still not in ES 3.0 either. Only in ES 3.1, glGetTexLevelParameteriv() was added, which gives you access to all the values you're looking for. For example to get the width and height of the currently bound texture:

int[] texDims = new int[2];
GLES31.glGetTexLevelParameteriv(GLES31.GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, texDims, 0);
GLES31.glGetTexLevelParameteriv(GLES31.GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, texDims, 1);


回答2:

As @Reto Koradi said there is no way to do it but you can store the width and height of a texture when you are loading it from android context before you bind it in OpenGL.

    AssetManager am = context.getAssets();
    InputStream is = null;
    try {
        is = am.open(name);
    } catch (IOException e) {
        e.printStackTrace();
    }
    final Bitmap bitmap = BitmapFactory.decodeStream(is);
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    // here is you bind your texture in openGL


回答3:

I'll suggest a hack for doing this. Use ESSL's textureSize function. To access its result from the CPU side you're going to have to pass the texture as an uniform to a shader, and output the texture size as the r & g components of your shader output. Apply this shader to an 1x1px primitive drawn to a 1x1px FBO, then readback the drawn value from the GPU with glReadPixels.

You'll have to be careful with rounding, clamping and FBO formats. You may need a 16-bit integer FBO format.