4
public Bitmap getBitmapFromGlSurface(int x, int y, int w, int h){
    ByteBuffer buff = ByteBuffer.allocate(h * w * 4);
    Bitmap bitmap;

    try {
        GLES20.glReadPixels(x, y, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buff);
        bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buff);
        Matrix matrix = new Matrix();
        matrix.postScale(1, -1, w / 2, h / 2); // We have to flip it upside down because opengl has inverted y axis
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);

    } catch (GLException e) {
        Log.d(TAG, "createBitmapFromGLSurface: " + e.getMessage(), e);
        return null;
    }
    return bitmap;
}

Calling this method from queueEvent of glSurfaceView

activity.glSurfaceView.queueEvent(new Runnable() {
        @Override
        public void run() {
            final Bitmap snapshotBitmap = activity.glSurfaceView.getRenderer().getBitmapFromGlSurface(0, 0, activity.glSurfaceView.getWidth(), activity.glSurfaceView.getHeight());

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bitmapReadyCallbacks.onBitmapReady(snapshotBitmap);
                }
            });
        }
    });

Here is the initialization of glSurfaceView

    setZOrderOnTop(true);
    setEGLContextClientVersion(2);
    setEGLConfigChooser(8, 8, 8, 8, 0, 0);
    getHolder().setFormat(PixelFormat.TRANSLUCENT);
    renderer = new WriteGLRenderer(activity,this);
    setRenderer(renderer);
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    setPreserveEGLContextOnPause(true); 
genpfault
  • 51,148
  • 11
  • 85
  • 139

1 Answers1

4

Because you are using setZOrderTop(true) in GLSurfaceView initialization, It won't let you go to its view and capture the pixels of it. In order to get bitmap you have to return the bytes array from JNI(C++) side code and put those pixels to buffer. Here is the method

    public Bitmap getBitmapFromGlSurface(int w, int h){
            Bitmap bitmap;
            try {
                ByteBuffer buff = ByteBuffer.wrap(WriteViewActivity.getSnapshot());
                buff.rewind();
                bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                bitmap.copyPixelsFromBuffer(buff);
                buff.clear();
                Matrix matrix = new Matrix();
                matrix.postScale(1, -1, bitmap.getWidth() / 2, bitmap.getHeight() / 2); // We have to flip it upside down because opengl has inverted y axis
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, (int)(bitmap.getWidth()), (int)(bitmap.getHeight() ), matrix, true);
            } catch (GLException e) {
                Log.e(TAG, "createBitmapFromGLSurface: " + e.getMessage(), e);
                return null;
            }
            return bitmap;
        }
Hassan Akram
  • 129
  • 3