如何在android中单击带有surfaceview的按钮时在前后摄像头之间切换

时间:2014-09-19 10:28:05

标签: android camera

我正在开发一个应用程序。我希望显示前后摄像头。当我打开应用程序时,它将显示后置摄像头它工作正常。但是当单击用于打开前置摄像头的按钮时,它不会显示。独立的前后摄像头完美运行。默认摄像头是后置摄像头,当点击按钮时它将改为前置摄像头再次单击该按钮它将变为后置摄像头。我可以这样做。请有人告诉我。我发送源代码请看一次告诉我代码中有什么错误。请告诉我对android开发的新手..

CamTestActivity.java


*public class CamTestActivity extends Activity {
 private static final String TAG = "CamTestActivity";
 Preview preview;
 Button buttonClick,savee,front,zoomin,zoomout;
 Camera camera;
 Activity act;
 Context ctx;
 ImageView imm,aboveimg;
 LayoutInflater controlInflater ;
 Camera.Parameters params;
 public RelativeLayout layout,rlayout;
 Bitmap bitmap=null;
 SurfaceHolder surfaceholder;
 int myScreenHeight = 0;
 int myScreenWidth = 0;
 Bitmap bmapoverlay;
 public static ZoomControls zoom;
 byte[] dataaa;
 Bitmap bitmapPicture;
 int  maxZoomLevel=0;
 int currentZoomLevel = 0;
 private int cameraId= Camera.CameraInfo.CAMERA_FACING_BACK;
 boolean inPreview;
 int currentCameraId;
 int which=0;
 private int cameraType;
 int camIdx = 0;
 boolean previewing = false;
 @SuppressLint("InlinedApi")
 int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
 int numberOfCamera;
 @SuppressLint("NewApi")
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ctx = this;
    act = this;
    setContentView(R.layout.main);
    layout=(RelativeLayout)findViewById(R.id.relative);
    rlayout=(RelativeLayout)findViewById(R.id.rrlayout);
    preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
    preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    imm=(ImageView)findViewById(R.id.imageView1);
    aboveimg=(ImageView)findViewById(R.id.imageView2);
    rlayout.addView(preview);
    aboveimg.setImageResource(R.drawable.design);
    //layout.setVisibility(View.GONE);
    preview.setKeepScreenOn(true);
    buttonClick = (Button)findViewById(R.id.btnCapture);
    // camera = openFrontFacingCameraGingerbread();
    zoomin=(Button)findViewById(R.id.button2);
    zoomout=(Button)findViewById(R.id.button3);
    front=(Button)findViewById(R.id.button1);
    //setCameraDisplayOrientation(CamTestActivity.this, currentCameraId, camera);
    buttonClick.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
            camera.takePicture(shutterCallback, rawCallback, jpegCallback);
        }
    });
    zoomin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            preview.zoom();
        }
    });
    zoomout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            preview.unzoom();
        }
    });
    /*// do we have a camera?
    if (!getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
        Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
        .show();
    } else {
        cameraId = findFrontFacingCamera();
        if (cameraId < 0) {
            Toast.makeText(this, "No front facing camera found.",
                    Toast.LENGTH_LONG).show();
        } else {
            camera = Camera.open(cameraId);
        }
    }*/
    front.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            openFrontFacingCamera();
        }
    });
    }
   @SuppressLint("NewApi")
   public void openFrontFacingCamera() {
    numberOfCamera = Camera.getNumberOfCameras();
    if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
        camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        Toast.makeText(getApplicationContext(), "BACK TO FRONT" ,
                1000).show();
        try {
            camera.stopPreview();
            camera.release();
            camera = Camera.open(camId);
            camera.setPreviewDisplay(surfaceholder);
            camera.startPreview();
            previewing = true;
        } catch (RuntimeException e) {
        } catch (IOException e) {}
     }else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
        camId = Camera.CameraInfo.CAMERA_FACING_BACK;
        Toast.makeText(getApplicationContext(), "FRONT TO BACK" , 1000).show();
        try {
            camera.release();
            camera = Camera.open(camId);
            camera.setPreviewDisplay(surfaceholder);
            camera.startPreview();
        } catch (RuntimeException e) {
        } catch (IOException e) {}
      }
    }
     /*@SuppressLint("NewApi")
    private int findFrontFacingCamera() {
    int cameraId = -1;
    // Search for the front facing camera
    int numberOfCameras = Camera.getNumberOfCameras();
    for (int i = 0; i < numberOfCameras; i++) {
        CameraInfo info = new CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
            // Log.d(DEBUG_TAG, "Camera found");
            cameraId = i;
            break;
        }
       }
      return cameraId;
   }*/
   @SuppressLint("NewApi")
   @Override
   protected void onResume() {
    super.onResume();
    //      preview.camera = Camera.open();
    camera = Camera.open();
    camera.startPreview();
    preview.setCamera(camera);
    //camera.stopPreview();
   }
   @Override
   protected void onPause() {
    if(camera != null) {
        camera.stopPreview();
        preview.setCamera(null);
        camera.release();
        camera = null;
    }
    super.onPause();
    }
    private void resetCam() {
    camera.startPreview();
    preview.setCamera(camera);
    }
    private void refreshGallery(File file) {
    Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    mediaScanIntent.setData(Uri.fromFile(file));
    sendBroadcast(mediaScanIntent);
    }
    ShutterCallback shutterCallback = new ShutterCallback() {
    public void onShutter() {
        //Log.d(TAG, "onShutter'd");
    }
    };
    PictureCallback rawCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        //           Log.d(TAG, "onPictureTaken - raw");
    }
    };
   PictureCallback jpegCallback = new PictureCallback() {
    @SuppressLint("NewApi")
    public void onPictureTaken(byte[] data, Camera camera) {
        //dataaa=data;
        //new SaveImageTask().execute(data);        
        bitmapPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
        imm.setImageBitmap(bitmapPicture);
        resetCam();
        FileOutputStream outStream = null;
        layout.getRootView();
        layout.setDrawingCacheEnabled(true);
        layout.buildDrawingCache();
        Bitmap m=layout.getDrawingCache();
        // Write to SD Card
        try {
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/camtest");
            dir.mkdirs();           
            String fileName = String.format("%d.jpg", System.currentTimeMillis());
            File outFile = new File(dir, fileName);
            outStream = new FileOutputStream(outFile);
            m.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            outStream.write(data[0]);
            outStream.flush();
            outStream.close();
            Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
            refreshGallery(outFile);
            imm.setVisibility(View.GONE);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        //buttonClick.setVisibility(View.GONE);
        //savee.setVisibility(View.VISIBLE);
        //Toast.makeText(getApplicationContext(), "display", 1000).show();
        Log.d(TAG, "onPictureTaken - jpeg");
        }
         };



  Preview.java

   class Preview extends ViewGroup implements SurfaceHolder.Callback {
   protected static final String camera = null;
   Camera.Parameters params;
  private final String TAG = "Preview";
  protected Camera.Size mPictureSize;
  protected Activity mActivity;
  SurfaceView mSurfaceView;
  SurfaceHolder mHolder;
   Size mPreviewSize;
  List<Size> mSupportedPreviewSizes;
  Camera mCamera;
  Context context;
  int currentZoomLevel ;
  int maxZoomLevel ;
  boolean previewing = false;
  int camId = Camera.CameraInfo.CAMERA_FACING_BACK;



   //private TutorialThread _thread;
  @SuppressWarnings("deprecation")
   Preview(Context context, SurfaceView sv) {
    super(context);
    mSurfaceView = sv;
    //        addView(mSurfaceView);
    mHolder = mSurfaceView.getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    //params = mCamera.getParameters();
    }
    public void setCamera(Camera camera) {
     mCamera = camera;
     if (mCamera != null) {
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        requestLayout();
        // get Camera parameters
        params = mCamera.getParameters();
        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            // set the focus mode
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            // set Camera parameters
            mCamera.setParameters(params);
        }
       }
     }
     @Override
       protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      // We purposely disregard child measurements because act as a
      // wrapper to a SurfaceView that centers the camera preview instead
       // of stretching it.
       final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
       final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
       setMeasuredDimension(width, height);
       if (mSupportedPreviewSizes != null) {
        mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }
        }
        @Override
       protected void onLayout(boolean changed, int l, int t, int r, int b) {
         if (changed && getChildCount() > 0) {
        final View child = getChildAt(0);
        final int width = r - l;
        final int height = b - t;
        int previewWidth = width;
        int previewHeight = height;
        if (mPreviewSize != null) {
            previewWidth = mPreviewSize.width;
            previewHeight = mPreviewSize.height;
        }
        // Center the child SurfaceView within the parent.
        if (width * previewHeight > height * previewWidth) {
            final int scaledChildWidth = previewWidth * height / previewHeight;
            child.layout((width - scaledChildWidth) / 2, 0,
                    (width + scaledChildWidth) / 2, height);
        } else {
            final int scaledChildHeight = previewHeight * width / previewWidth;
            child.layout(0, (height - scaledChildHeight) / 2,
                    width, (height + scaledChildHeight) / 2);
        }
        }
        }
      @SuppressLint({ "WrongCall", "NewApi" })
       public void surfaceCreated(final SurfaceHolder holder) {
     // The Surface has been created, acquire the camera and tell it where
     // to draw.
     /* params.setRotation(90);
      mCamera.setDisplayOrientation(90);*/
      try {
        if (mCamera != null) {
           // mCamera=Camera.open(camId);
            mCamera.setPreviewDisplay(holder);
            params = mCamera.getParameters();
            params.set("orientation", "portrait");
            params.setRotation(90);
            mCamera.setDisplayOrientation(90);
            mCamera.setParameters(params);

            //////////


        }
       } catch (IOException exception) {
        Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
         }
        }

      public void surfaceDestroyed(SurfaceHolder holder) {
         // Surface will be destroyed when we return, so stop the preview.
          if (mCamera != null) {
           mCamera.stopPreview();
           mCamera.release();
            mCamera = null;
            previewing = false;
         }
         }
         private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
       final double ASPECT_TOLERANCE = 0.1;
         double targetRatio = (double) w / h;
        if (sizes == null) return null;
          Size optimalSize = null;
         double minDiff = Double.MAX_VALUE;
            int targetHeight = h;
           // Try to find an size match aspect ratio and size
               for (Size size : sizes) {
         double ratio = (double) size.width / size.height;
         if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
         if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
           }
           }
           // Cannot find the one match the aspect ratio, ignore the requirement
             if (optimalSize == null) {
              minDiff = Double.MAX_VALUE;
           for (Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
            }
              }
           return optimalSize;
            }
         public void zoom()
          {

        params=mCamera.getParameters();
        maxZoomLevel = params.getMaxZoom();
        if (currentZoomLevel < maxZoomLevel) {
            currentZoomLevel++;
            params.setZoom(currentZoomLevel);
            mCamera.setParameters(params);
        }
        /*if(currentZoomLevel < 50){
        params.setZoom(currentZoomLevel= currentZoomLevel + 10);
        mCamera.setParameters(params);   
        }else{

        Toast.makeText(getContext(), "no zoom here..",Toast.LENGTH_LONG).show();
        }*/

          }
    public void unzoom()
    {
        params=mCamera.getParameters();
        maxZoomLevel = params.getMaxZoom();
        if (currentZoomLevel > 0) {
            currentZoomLevel--;
            params.setZoom(currentZoomLevel);
            mCamera.setParameters(params);
        }
        /*if(currentZoomLevel >0){
        params.setZoom(currentZoomLevel= currentZoomLevel - 10);
        mCamera.setParameters(params);
        }else{
            mCamera.setParameters(params);
        }
       */
      }
       public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
       if(previewing){
        mCamera.stopPreview();
        previewing = false;
     }
      // params=mCamera.getParameters();
     if(mCamera != null) {
        params=mCamera.getParameters();
        params.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        requestLayout();
        mCamera.setParameters(params);
        //mCamera.setParameters(cameraParams);
        //mCamera.setDisplayOrientation(90);
        mCamera.startPreview();
        previewing=true;


        }

        }
        }*

1 个答案:

答案 0 :(得分:0)

将此方法用于前置摄像头:

private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx<cameraCount; camIdx++) {
    Camera.getCameraInfo(camIdx, cameraInfo);
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        try {
            cam = Camera.open(camIdx);
        } catch (RuntimeException e) {
            Log.e("Your_TAG", "Camera failed to open: " + e.getLocalizedMessage());
        }
    } 
    return cam;
}

参考this