我尝试使用Camera2 API获取摄像头的每一帧进行图像处理,但是遇到一个致命错误,提示:
FATAL EXCEPTION: main Process: com.example.avoor.camera2api, PID: 2831 java.lang.IllegalStateException: Image is already closed
我成功地打开了相机并将其发送到TextureView进行预览,但是当涉及到OnImageAvailableListener时,应用程序会崩溃。
这是使用的代码:
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
ImageReader reader = ImageReader.newInstance(640, 480, ImageFormat.YUV_420_888, 3);
//reader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
captureRequestBuilder.addTarget(reader.getSurface());
List<Surface> outputSurfaces = new ArrayList<>();
outputSurfaces.add(reader.getSurface());
outputSurfaces.add(surface);
///////////////////////////////////////////////////////////////////
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = reader.acquireLatestImage();
final byte[] bytes;
bytes = convertYUV420888ToNV21(image);
Log.d(TAG,"Height:"+String.valueOf(image.getHeight())+
" Width: "+String.valueOf(image.getWidth()));
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bitmap);
}
}
});
}
catch (IllegalStateException e) {
Log.e(TAG, "Too many images queued for saving, dropping image for request: ");
return;
}
finally {
if (image != null) {
image.close();
}
}
}
};
reader.setOnImageAvailableListener(readerListener, mBackgroundHandler);
///////////////////////////////////////////////////////////////////
cameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback(){
@Override
public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
并且在这里:
protected void updatePreview() {
if(null == cameraDevice) {
Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
当相机打开时,我已经启动了BackgroundThread