拍照在真实设备上崩溃

时间:2014-07-22 19:48:04

标签: android image crash

我正在使用此代码拍照并在模拟器中正常工作。它不适用于物理移动设备,并且在Samsung Galaxy S4和Sony Xperia Z2上出错。

我的代码:

private void takePicture() {
    openCamera();
    camera.takePicture(new ShutterCallback() {
        @Override
        public void onShutter() {
        }
    }, new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
        }
    }, new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
            img_screenshot.setImageBitmap(bitmap);
            closeCamera();
        }
    });
}

private void openCamera() {
    camera = Camera.open();
    Camera.Parameters params = camera.getParameters();
    List<Size> sizes = params.getSupportedPictureSizes();
    Size mSize = sizes.get(0);
    params.setPictureSize(mSize.width, mSize.height);
    camera.setParameters(params);
}

private void closeCamera() {
    camera.release();
}

1 个答案:

答案 0 :(得分:2)

首先确保在清单中使用权限

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

之后,在调用takePicture之前,调用startPreview,如:

private void takePicture() {
    openCamera();
    camera.startPreview();
    camera.takePicture(new ShutterCallback() {

        @Override
        public void onShutter() {
        }
    }, new PictureCallback() {

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

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
            img_screenshot.setImageBitmap(bitmap);
            closeCamera();
        }
    });
}

private void openCamera() {
    camera = Camera.open();
    Camera.Parameters params = camera.getParameters();
    List<Size> sizes = params.getSupportedPictureSizes();
    Size mSize = sizes.get(0);
    params.setPictureSize(mSize.width, mSize.height);
    camera.setParameters(params);
}

private void closeCamera() {
    camera.release();
}