看到网上关于这个大部分写的都不对,贴下正确代码
private void captureBitmap() {
glSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
EGL10 egl = (EGL10) EGLContext.getEGL();
GL10 gl = (GL10) egl.eglGetCurrentContext().getGL();
snapshotBitmap = createBitmapFromGLSurface(0, 0, glSurfaceView.getWidth(), glSurfaceView.getHeight(), gl);
if (snapshotBitmap == null) {
return;
}
int width = snapshotBitmap.getWidth();
int height = snapshotBitmap.getHeight();
if (width > 0 && height > 0) {
// 这里拿到Bitmap用来处理
} else {
Log.e("cxl", "没有二维码");
mHandler.postDelayed(VideoChatActivity.this, 1000);
}
} else {
Log.e("cxl", "width==" + width);
Log.e("cxl", "height==" + height);
mHandler.postDelayed(VideoChatActivity.this, 1000);
}
}
});
}
private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
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) {
Log.e("cxl", "createBitmapFromGLSurface: " + e.getMessage(), e);
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}