一、预览Camera数据
做过Android开发的人一般都知道,有两种方法能够做到这一点:SufaceView、TextureView。
- 下面是使用SurfaceView预览数据的方式:
SurfaceView surfaceView;
Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(this);
// 打开摄像头并将展示方向旋转90度
camera = Camera.open();
camera.setDisplayOrientation(90);
}
//------ Surface 预览 -------
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int w, int h) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.release();
}
- 下面是使用TextureView预览数据的方式:
TextureView textureView;
Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureView = (TextureView) findViewById(R.id.texture_view);
textureView.setSurfaceTextureListener(this);// 打开摄像头并将展示方向旋转90度
camera = Camera.open();
camera.setDisplayOrientation(90);
}
//------ Texture 预览 -------
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
try {
camera.setPreviewTexture(surfaceTexture);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
camera.release();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
二、取到NV21的数据回调
Android 中Google支持的Camera Preview CallBack的YUV常用格式有两种:一种是NV21,一种是YV12,Android一般默认使用的是YCbCR_420_sp(NV21)
- 我们可以配置数据回调的格式:
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewFormat(ImageFormat.NV21);
camera.setParameters(parameters);
- 通过setPreviewCallback方法监听预览的回调:
这里面的Bytes的数据就是NV21格式的数据。