Android - Take picture without preview

2019-01-18 14:02发布

问题:

I am trying to take a picture without preview, immediately when my application starts running and after that to save the picture in new folder - "pictures123", in the root folder. Could someone please tell me what's wrong in my code?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File directory = new File(Environment.getExternalStorageDirectory() + "/pictures123/");

    if (!directory.exists()) {
        directory.mkdir();
    }

    Camera camera = Camera.open(0);
    Camera.Parameters parameters = camera.getParameters();
    parameters.setPictureFormat(ImageFormat.JPEG);
    camera.setParameters(parameters);
    SurfaceView mview = new SurfaceView(getBaseContext());
    camera.setPreviewDisplay(mview.getHolder());
    camera.setPreviewDisplay(null);
    camera.startPreview();
    camera.takePicture(null,null,photoCallback);
    camera.stopPreview();
}

Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {

        try {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/pictures123");
            File file = new File (myDir, "pic1.jpeg");
            FileOutputStream out = new FileOutputStream(file);
            out.write(data);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        finish();

    }
};

permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

回答1:

You can't take a picture without a preview, but you don't have to show the preview on screen. You can direct the output to a SurfaceTexture instead (API 11+).

See this answer for more details.



回答2:

I think the main problem is that you are calling takePicture immediately after startPreview which actually takes time to complete its setup. So adding a delay between those two could temporarily fix this issue, look here for more details.



回答3:

It's impossible to take a picture without preview. You should read the Android online reference: http://developer.android.com/reference/android/hardware/Camera.html#takePicture.

Note: This method is only valid when preview is active (after startPreview()). Preview will be stopped after the image is taken; callers must call startPreview() again if they want to re-start preview or take more pictures. This should not be called between start() and stop().