Android Camera:在按钮点击上调用预览回调

时间:2014-08-22 00:37:44

标签: java android android-camera onclicklistener

在framelayout中显示相机。我想通过按钮点击从相机获取PreviewFrames。但我不知道该怎么做,因为我是一个Android新手。任何帮助将不胜感激。谢谢

我的代码如下:

    public class MainActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mPreview;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mCamera = getCameraInstance();

    // Create our Preview view and set it as the content of our activity.
    mPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    mCamera.setDisplayOrientation(90);
    preview.addView(mPreview);


      findViewById(R.id.capture).setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {


           }
        });         

    }

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
   }



   public static Camera getCameraInstance(){
    Camera c = null;
    try {
        c = Camera.open(); // attempt to get a Camera instance
    }
    catch (Exception e){
        // Camera is not available (in use or does not exist)
    }
    return c; // returns null if camera is unavailable
  }






public void onPreviewFrame(byte[] data, Camera camera) {
    try {
        Camera.Parameters parameters = camera.getParameters();
        Size size = parameters.getPreviewSize();
        YuvImage image = new YuvImage(data, parameters.getPreviewFormat(),
                size.width, size.height, null);
        File file = new File(Environment.getExternalStorageDirectory()
                .getPath() + "/out.jpg");
        FileOutputStream filecon = new FileOutputStream(file);
        image.compressToJpeg(
                new Rect(0, 0, image.getWidth(), image.getHeight()), 90,
                filecon);
     } catch (FileNotFoundException e) {
        Toast toast = Toast
                .makeText(getBaseContext(), e.getMessage(), 1000);
        toast.show();
    }
    }



    }

2 个答案:

答案 0 :(得分:1)

首先,抱歉我的可怜的英格! 做“#34;获取相机预览帧"是不是想拍照? 如果正确,您可以在Camera类中使用方法takePicture() 如果没有,你可以在onPreviewFrame方法中使用一个标志,你可以通过onClickListener将其改为true,并且在做了之后应该改为false

答案 1 :(得分:0)

OnPreviewFrame()是PreviewCallback接口中的一个方法。所以我认为你需要创建一个实现该接口的类,并使用该对象调用camera.setPreviewCallback()。 小心原因OnPreviewFrame在每次帧可用时被调用a.k.a它将在预览运行时被多次调用。