我正在使用此代码拍照并在模拟器中正常工作。它不适用于物理移动设备,并且在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();
}
答案 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();
}