Camerax 拍照 image.planes 始终为空

Camerax Take Picture image.planes always empty

我尝试为内存使用拍摄图像,但 imageProxy.planes[0].remaining() 始终为 0。因此我无法从结果中获取位图。这是错误还是我做错了什么?

这是我绑定相机的方法:

private fun bindPreview(cameraProvider: ProcessCameraProvider) {
    val cameraSelector: CameraSelector = CameraSelector.Builder()
        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
        .build()

    imageCapture = ImageCapture.Builder()
        .setCaptureMode((ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY))
        .setTargetAspectRatio(aspectRatio)
        .setTargetRotation(rotation)
        .build()

    imageAnalyzer = ImageAnalysis.Builder()
        .setTargetAspectRatio(aspectRatio)
        .setTargetRotation(rotation)
        .build()

    imageAnalyzer?.setAnalyzer(cameraExecutor, ImageAnalysis.Analyzer { image ->
        viewModel.analyzeImage(image)
    })

    preview = Preview.Builder()
        .setTargetAspectRatio(aspectRatio)
        .setTargetRotation(rotation)
        .build()

    cameraProvider.unbindAll()

    try {
        camera = cameraProvider.bindToLifecycle(
            this as LifecycleOwner,
            cameraSelector,
            preview,
            imageCapture,
            imageAnalyzer
        )
        preview?.setSurfaceProvider(binding.previewView.createSurfaceProvider(camera?.cameraInfo))
    } catch (e: Exception) {
        Timber.e(e, "Could not bind camera.")
    }
}

下面是我尝试捕获图像的代码:

imageCapture?.takePicture(cameraExecutor, object : ImageCapture.OnImageCapturedCallback() {
        override fun onCaptureSuccess(image: ImageProxy) {
            Log.d(
                "test",
                "image -> height: ${image.height} | width: ${image.width} | format: ${image.format}"
            )
            Log.d(
                "test",
                "image -> planes.size ${image.planes.size} | planes[0].buffer.remaining ${image.planes[0].buffer.remaining()}"
            )
            Log.d(
                "test",
                "image -> image.image?.planes.size ${image.image?.planes?.size} | image.image?.planes[0].buffer.remaining ${image.image!!.planes[0].buffer.remaining()}"
            )

            // some code here

            image.close()
        }

        override fun onError(exception: ImageCaptureException) {
            super.onError(exception)
            Timber.e(exception.cause, "Could not capture image.")
        }
    })
}

截取的图像的高度和宽度似乎是正确的。

首先,不要对image.image!!进行操作。 尝试倒带 ByteBuffer 然后检查 remaining() 尝试:

val buffer = image.planes[0].buffer
buffer.rewind()