android 调用系统前置摄像头

  从Android 2.3 Gingerbread开始,原生支持前置摄像头。下面我们看看如何在程序里来调用前置的摄像头。


    第一种方式是采用MediaStore,调用系统原生的相机。

view plain
  1. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  2.         
  3. intent.putExtra("camerasensortype", 2); // 调用前置摄像头  
  4. intent.putExtra("autofocus", true); // 自动对焦  
  5. intent.putExtra("fullScreen", false); // 全屏  
  6. intent.putExtra("showActionIcons", false);  
  7.   
  8. startActivityForResult(intent, PICK_FROM_CAMERA);  

    另外一种方式是采用Camera框架,以前版本的SDK里只有Camera.open()方法来调用后置摄像头,现在此方法接受一个参数来确定是前置摄像头还是后置摄像头。我们还根据新的Camerainfo类和getCameraInfo方法来获取Android设备上的详细的摄像头信息,getNumberOfCameras()来获取摄像头的数量。典型的调用方式如下:

view plain
  1. int cameraCount = 0;  
  2. Camera cam = null;  
  3.   
  4. Camera.CameraInfo cameraInfo = new Camera.CameraInfo();  
  5. cameraCount = Camera.getNumberOfCameras(); // get cameras number  
  6.         
  7. for ( int camIdx = 0; camIdx < cameraCount;camIdx++ ) {  
  8.     Camera.getCameraInfo( camIdx, cameraInfo ); // get camerainfo  
  9.     if ( cameraInfo.facing ==Camera.CameraInfo.CAMERA_FACING_FRONT ) { // 代表摄像头的方位,目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置  
  10.         try {              
  11.             cam = Camera.open( camIdx );  
  12.         } catch (RuntimeExceptione) {  
  13.             e.printStackTrace();  
  14.     }  
  15. }  

 

     采用Camera框架的好处在于自身提供了大量的API例如setDisplayOrientation、Camera.Parameters来实现强大的功能,另外结合urfaceHolder.Callback、ShutterCallback和PictureCallback等接口后可以进行界面和功能的自定义,可以自由的实现所需要的界面布局和图像处理效果。例如如下的界面:



你可能感兴趣的:(android)