【发布时间】:2016-03-03 05:49:34
【问题描述】:
我正在尝试从 WebRTC Android 应用程序中保存帧。在SurfaceViewRenderer.java 中,它使用 GLES 着色器绘制 YUV 帧。为了保存绘制的框架,我将 grafika 中的 saveFrame() 添加到 SurfaceViewRenderer.java 但是当我调用 saveFrame() 时它不起作用(位图为空)。我以为 glReadPixels() 从当前颜色缓冲区读取像素,但似乎在当前 EGLcontext 中没有调用它?如何调用 glReadPixels() 保存当前帧?
我写的代码是这样的:
在 MainActivity 我添加了这样的按钮。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bitmap = localSurfaceViewRender.saveFrame();
if (bitmap != null) {
Toast.makeText(getApplicationContext(), "Saved!!", Toast.LENGTH_SHORT).show();
imageView.setImageBitmap(bitmap);
}
}
});
在 SurfaceViewRenderer.java 中,我添加了一些方法来从当前绑定的 egl 中获取值
public int getSurfaceHeight() {
if (mHeight < 0) {
return eglBase.surfaceHeight();
} else {
return mHeight;
}
}
public int getSurfaceWidth() {
if (mWidth < 0) {
return eglBase.surfaceWidth();
} else {
return mWidth;
}
}
public Bitmap saveFrame() {
int width = eglBase.surfaceWidth();
int height = eglBase.surfaceHeight();
ByteBuffer buf = ByteBuffer.allocateDirect(width * height * 4);
buf.order(ByteOrder.LITTLE_ENDIAN);
GLES20.glFinish();
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGB, GLES20.GL_UNSIGNED_BYTE, buf);
GlUtil.checkNoGLES2Error("glReadPixels");
buf.rewind();
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
return bmp;
}
编辑: 这段代码是saveFrame的完整代码
// save as a file
public void saveFrame(final File file) {
runOnRenderThread(new Runnable() {
@Override
public void run() {
int width = eglBase.surfaceWidth();
int height = eglBase.surfaceHeight();
ByteBuffer buf = ByteBuffer.allocateDirect(width * height * 4);
buf.order(ByteOrder.LITTLE_ENDIAN);
GLES20.glFinish();
GLES20.glReadPixels(0, 0, width, height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf);
GlUtil.checkNoGLES2Error("glReadPixels");
buf.rewind();
// fliping by vertical
byte[] tmp = new byte[width * 4];
for (int i = 0; i < height / 2; i++) {
buf.get(tmp);
System.arraycopy(buf.array(), buf.limit() - buf.position(),
buf.array(), buf.position() - width * 4, width * 4);
System.arraycopy(tmp, 0, buf.array(), buf.limit() - buf.position(), width * 4);
}
buf.rewind();
String filename = file.toString();
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(filename));
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bmp.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (bos != null) try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Saved " + width + "x" + height + " frame as '" + filename + "'");
}
});
}
【问题讨论】:
标签: android opengl-es surfaceview