无法在android中拍照

时间:2014-04-09 00:41:52

标签: android camera

我试图使用下面的代码在Android中拍照。目前的代码不起作用,即我无法在手机的存储空间内找到图片。

public class CameraShooting implements SurfaceHolder.Callback {

    Context context;
    Camera camera;
    CameraInfo camerainfo;
    Camera.Parameters paras;
    SurfaceView surfaceview;
    SurfaceHolder surfaceholder;
    PictureCallback picturecallback;
    SurfaceHolder.Callback callback = (SurfaceHolder.Callback) this;

    public CameraShooting(Context context) {

        this.context = context;
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            surfaceview = new SurfaceView(context);

            surfaceholder = surfaceview.getHolder();
            surfaceholder.addCallback(callback);

        }

    };

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        int numbersofCamera = camera.getNumberOfCameras();
        camerainfo = new CameraInfo();
        /*
         * for(int i =0; i < numbersofCamera; i++){ Camera.getCameraInfo(i,
         * camerainfo); if (camerainfo.facing ==
         * CameraInfo.CAMERA_FACING_FRONT){ camera.open(i); }}
         */

        camera.open(0);
        try {
            camera.setPreviewDisplay(surfaceholder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        camera.startPreview();
        camera.takePicture(null, null, mPicture);
        Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
    };

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    private PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            File pictureFile = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS
                    ), "picture taken");
            try {
                OutputStream fos = new BufferedOutputStream(new FileOutputStream(pictureFile));
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {

            }
        };
    };

}

注意,我已经包括

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

1 个答案:

答案 0 :(得分:1)

尝试:

fos.flush();

关闭OutputStream

之前