@chopsticks
2015-09-23T15:11:23.000000Z
字数 2954
阅读 2224
Android
Development
tags:Android, Development
Android上的应用开发主要参考Google官方关于Camera的开发说明,其中包含了关于TakePicture和CaptureVideo的示例代码片段。
要点:必须使用Preview来实现capture picture或video
OnPictureTaken
方法。在该SurfaceHolder中处理所有有关Preivew和Camera相关的事情。需要定义:
实现SurfaceHolder
的回调--SurfaceHolderCallback
,以便自动处理Holder发生变化的一些event。
具体代码如下:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
public final String TAG = "CameraPreview";
private Camera mCamera = null;
private CameraUtil mCameraUtil;
private SurfaceHolder mSurfaceHolder;
private Camera.PictureCallback mPicture;
CameraPreview(Context context){
super(context);
mCameraUtil = new CameraUtil(context);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//process image data
...
//start preview again
camera.startPreview();
}
};
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int w, int h){
if(mSurfaceHolder.getSurface()==null){
//preview surface doesnot exist
return;
}
try {
mCamera.stopPreview();
}catch (Exception e){
Log.i(TAG, "STOP preview ERROR:"+e.getMessage());
}
// set preview size and make any resize, rotate or
// reformatting changes here
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
}catch (Exception e){
Log.i(TAG, "start preview error: "+e.getMessage());
}
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder){
try {
//open camera
mCamera = mCameraUtil.getCameraInstance();
}catch (Exception e){
Log.i(TAG, "Camera open failed!"+ e.getMessage());
return;
}finally {
if(mCamera == null) {
Log.i(TAG, "open camera failed");
return;
}
}
try {
//set preview
mCamera.setPreviewDisplay(mSurfaceHolder);
//start preview
mCamera.startPreview();
}catch (Exception e){
Log.i(TAG, "error setting camera preview:"+e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder){
mCamera.stopPreview();
mCamera.release();
mCamera = null;
Log.i(TAG, "preview destroyed");
}
public void takePicture(){
mCamera.takePicture(null,null, mPicture);
Log.i(TAG, "picture taked!");
}
public Camera getCamera(){
return mCamera;
}
...
}
startPreview
,这时候需要人工的在OnPictureTaken回调函数里边,加上startPreview
:
mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera){
//image data process
...
//start preview again
mCamera.startPreview();
}
};
并将继承了SurfaceView的CameraView绑定到Frame上。
mCameraPreview = new CameraPreview(this);
cameraFrame.addView(mCameraPreview);
通过Button调用takePicture来拍照
mCameraPreview.takePicture()