Search code examples
androidimage-processingopengl-esbitmapscreenshot

Android opengl screenshot with alpha channel support


I'm currently developing an augmented reality application in android. Textured openGL object is drawn over the camera view. I had tried so many methods to take the screen shot of android openGL view (GLSurfaceview). But no success. I want the screenshot with transparent background so that I could draw it over camera image to produce an ARImage. Can any one help me? I know that I have to read the pixels of opengl using glReadPixels() function. I tried it using GL_RGBA mode and created bitmap (used ARGB_8888 and RGB_565). Using ARGB_8888 format I'll get a transparent image with no object and in RGB_565 mode I'll get a image filled with black color. Can any one guide me? Thanks in advance.

Thanks, Midhun


Solution

  • Hi I found the solution to my question and I'll paste the code here. It may be useful for others who need alpha support.

    public static Bitmap SavePixels(int x, int y, int w, int h, GL10 gl)
    {  
         int b[]=new int[w*(y+h)];
         int bt[]=new int[w*h];
         IntBuffer ib=IntBuffer.wrap(b);
         ib.position(0);
         gl.glReadPixels(x, 0, w, y+h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);
    
         for(int i=0, k=0; i<h; i++, k++)
         {//remember, that OpenGL bitmap is incompatible with Android bitmap
          //and so, some correction need.        
              for(int j=0; j<w; j++)
              {
                   int pix=b[i*w+j];
                   int pb=(pix>>16)&0xff;
                   int pr=(pix<<16)&0x00ff0000;
                   int pix1=(pix&0xff00ff00) | pr | pb;
                   bt[(h-k-1)*w+j]=pix1;
              }
         }
    
    
         Bitmap sb=Bitmap.createBitmap(bt, w, h, Bitmap.Config.ARGB_8888);
         return sb;
    }