我尝试使用camera2 API捕获图像。有时它会给出一些损坏/不完整的图像。
我要实现的流程是什么? 单击图像->使用ImageReader收听注册摄像机的捕获->将这些字节提供给将图像保存在图库中的函数。
这将导致图像不完整/损坏。 (并非总是如此,但至少有五分之三。)
我几乎尝试了所有可以在网上找到的东西。我认为这里的代码流有问题。
下面的代码是开始捕获的过程。
mState =“ CLICK”; cameraCaptureSessions?.capture(captureRequestBuilder?.build(),captureCallback,mBackgroundHandler)
Capture Builder,用于将Surface设置为图像读取器并创建以下捕获会话:
var capture_builder =
cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
capture_builder.addTarget(reader.surface)
var rotation = getWindowManager().getDefaultDisplay().getRotation();
capture_builder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
capture_builder.set(CaptureRequest.JPEG_QUALITY, 70);
capture_builder.set(CaptureRequest.NOISE_REDUCTION_MODE,CameraCharacteristics.NOISE_REDUCTION_MODE_HIGH_QUALITY)
capture_builder.set(CaptureRequest.CONTROL_AF_MODE,CameraCharacteristics.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
val captureCallback_in = object : CameraCaptureSession.CaptureCallback() {
override fun onCaptureProgressed(session: CameraCaptureSession,
request: CaptureRequest,
partialResult: CaptureResult)
{}
override fun onCaptureCompleted(session: CameraCaptureSession,
request: CaptureRequest,
result: TotalCaptureResult) {
cameraCaptureSessions = session
cameraCaptureSessions?.capture(captureRequestBuilder?.build(),captureCallback,mBackgroundHandler) mState = "PREVIEW";
cameraCaptureSessions?.setRepeatingRequest(captureRequestBuilder?.build(),
captureCallback, mBackgroundHandler);
}
}
cameraCaptureSessions!!.stopRepeating()
cameraCaptureSessions!!.capture(capture_builder.build(),
captureCallback_in,mBackgroundHandler);
这是图像侦听器,用于从图像获取字节:
private var readerListener = ImageReader.OnImageAvailableListener {
var image: Image? = null;
try {
image = it.acquireLatestImage()
var buffer = image.getPlanes()[0].getBuffer();
buffer.rewind()
var bytes = ByteArray(buffer.remaining())
buffer.get(bytes);
onPictureTaken(bytes);
} catch (e: FileNotFoundException) {
e.printStackTrace();
} catch (e: IOException) {
e.printStackTrace();
} finally {
if (image != null) {
image.close();
}
}
}
OnPictureTaken将图像保存到图库。