android平台opengl es读取纹理数据并保存图片

在AR云渲染服务中,有时候需要把生成的纹理保存到图片来进行调试。

那就想办法看看存成图片,很多人说用glGetTexImage这个函数可以直接读取纹理的数据,但是我们用到了opengl es 32版本,不支持这个函数,想了办法,把纹理绑定到framebuffer,然后用glReadPixels读取出来,然后在保存图片。

具体实现如下:

    private void saveRgb2Bitmap(Buffer buf, String filename, int width, int height) {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(filename));
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.copyPixelsFromBuffer(buf);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, bos);
            bmp.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveTextureToImage(int textureID, int width, int height, String fileName) {
        int[] frameBuffer = new int[1];
        GLES32.glGenFramebuffers(1, frameBuffer, 0);

        GLES32.glBindFramebuffer(GLES32.GL_FRAMEBUFFER, frameBuffer[0]);
        GLES32.glFramebufferTexture2D(GLES32.GL_FRAMEBUFFER, GLES32.GL_COLOR_ATTACHMENT0, GLES32.GL_TEXTURE_2D, textureID, 0);

        GLES32.glDrawBuffers(1, new int[]{GLES32.GL_COLOR_ATTACHMENT0}, 0);

        if (GLES32.glCheckFramebufferStatus(GLES32.GL_FRAMEBUFFER) != GLES32.GL_FRAMEBUFFER_COMPLETE) {
            Log.e(TAG, "framebuffer not complete");
            return;
        }

        ByteBuffer rgbaBuf = ByteBuffer.allocateDirect(width * height * 4);
        rgbaBuf.position(0);
        GLES32.glReadPixels(0, 0, width, height, GLES32.GL_RGBA, GLES32.GL_UNSIGNED_BYTE, rgbaBuf);

        saveRgb2Bitmap(rgbaBuf, fileName, width, height);

        GLES32.glDeleteFramebuffers(1, IntBuffer.wrap(frameBuffer));
        GLES32.glBindFramebuffer(GLES32.GL_FRAMEBUFFER, 0);
        ShaderUtil.checkGlError(TAG, "glCsInit end.");
    }

在其他地方调用就可以了。

String destDir = mContext.getExternalFilesDir(null).getAbsolutePath();
String fileName = destDir + "/" + System.nanoTime() + ".png";
saveTextureToImage(mCsImageIDs[1], width / 2, height, fileName);

glReadPixels函数是一个非常耗时的操作,我们只能当做调试来用。

参考文献:

https://blog.piasy.com/2016/06/14/Open-gl-es-android-2-part-2/index.html

https://stackoverflow.com/questions/53993820/opengl-es-2-0-android-c-glgetteximage-alternative

https://www.khronos.org/opengl/wiki/GLAPI/glGetTexImage

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XR风云

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值