0

I am doing the following to get the bitmap image that has been set to a GLSurfaceView object:

glView.setDrawingCacheEnabled(true);
glView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
glView.layout(0, 0, glView.getMeasuredWidth(), glView.getMeasuredHeight());

glView.buildDrawingCache(true);
Bitmap tmpbm = Bitmap.createBitmap(glView.getDrawingCache());
glView.setDrawingCacheEnabled(false);

But glView.getDrawingCache() is returning me null in the above case, and hence it is crashing in the line Bitmap tmpbm = Bitmap.createBitmap(glView.getDrawingCache()); Why am I getting null from there, and how do I tackle this issue? Also, is there a different / better way to achieve my goal? Any help would be highly appreciated.

Sanjiban Bairagya
  • 704
  • 2
  • 12
  • 33
  • See http://stackoverflow.com/questions/27817577/android-take-screenshot-of-surface-view-shows-black-screen . The code in the answer from @Helmi should work so long as you call it from `onDrawFrame()`. – fadden Jan 02 '16 at 21:52

1 Answers1

0

Try this method :

private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl)
        throws OutOfMemoryError {
    int bitmapBuffer[] = new int[w * h];
    int bitmapSource[] = new int[w * h];
    IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
    intBuffer.position(0);

    try {
        gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, intBuffer);
        int offset1, offset2;
        for (int i = 0; i < h; i++) {
            offset1 = i * w;
            offset2 = (h - i - 1) * w;
            for (int j = 0; j < w; j++) {
                int texturePixel = bitmapBuffer[offset1 + j];
                int blue = (texturePixel >> 16) & 0xff;
                int red = (texturePixel << 16) & 0x00ff0000;
                int pixel = (texturePixel & 0xff00ff00) | red | blue;
                bitmapSource[offset2 + j] = pixel;
            }
        }
    } catch (GLException e) {
        return null;
    }

    return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}

more here

Community
  • 1
  • 1
Helmi
  • 556
  • 2
  • 19
  • Can you kindly tell me what should I pass as parameters to the function `private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl)`? `gl` I am getting from the `onDrawFrame` function itself. Similarly, I have values for `w` and `h` as well (width and height of image). But what should be the values of `x` and `y`? – Sanjiban Bairagya Jan 04 '16 at 09:53
  • x & y represent the point of start when reading pixels. you could use 0 for both if you want to get all the surface. otherwise use the portion that you need. – Helmi Jan 04 '16 at 10:33