GLSurfaceView 截取图像的时候,往往传统的方法并不行得通,我们发现使用 GLSurfaceView.getDrawingCache() 等方法得到的往往是一张纯黑的图,这是由于 GLSurfaceView 和 SurfaceView 一样都有一块透明的缓存区域,所以我们截取的往往只是这块透明的缓存区域。
方法一:
下面这个方法是在 stackoverflow 上看到的一个方法,亲测可行
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) {
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}
截图的代码
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
// 获取GLSurfaceView的图片并保存
if (isTakePicture) {
Bitmap bmp = createBitmapFromGLSurface(0, 0, mOutputWidth,
mOutputHeight, gl);
isTakePicture = false;
}
因为onDrawFrame方法会被一直调用,所以我们需要控制一下截图的逻辑条件
方法二:
这个方法也是我们项目中用到的一些截取图片的方法,也是可以用的
private ByteBuffer mCaptureBuffer;
@Override
public void onDrawFrame(GL10 arg0) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
surfaceTexture.updateTexImage();
draw();
if (isTakePic) {
mCaptureBuffer.rewind();
GLES20.glReadPixels(0, 0, mOutputWidth, mOutputHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE,
mCaptureBuffer);
isTakePic = false;
new Thread(new Runnable() {
@Override
public void run() {
mCaptureBuffer.rewind();
mBitmap.copyPixelsFromBuffer(mCaptureBuffer);
String imageName = "Image_" + System.currentTimeMillis() + ".jpg";
BitmapUtils.saveBitmap(mBitmap, "/sdcard/face/", imageName);
}
}).start();
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
mOutputWidth = width;
mOutputHeight = height;
mCaptureBuffer = ByteBuffer.allocate(mOutputWidth * mOutputHeight * 4);
mBitmap = Bitmap.createBitmap(mOutputWidth, height, Config.ARGB_8888);
GLES20.glViewport(0, 0, width, height);
mFilter.onOutputSizeChanged(width, height);
}