首页 > 解决方案 > 将 imageProxy 转换为位图时,cameraX 图像已关闭

问题描述

我正在尝试使用以下函数将cameraX的拍照方法捕获的图像转换为位图

fun imageProxyToBitmap(image: ImageProxy): Bitmap {

    val buffer: ByteBuffer = image.planes[0].buffer // :- This line is where error was occurring

    buffer.rewind()
    val bytes = ByteArray(buffer.capacity())
    buffer.get(bytes)
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}

但它给出了一个错误

java.lang.IllegalStateException: Image is already closed

我正在使用最新版本的 cameraX 库"1.0.0-beta11"

如何解决这个问题?

标签: javaandroidkotlinandroid-bitmapandroid-camerax

解决方案


这工作正常

override fun onCaptureSuccess(image: ImageProxy) {
        var capturedImageBitmap = AppUtils().imageProxyToBitmap(image)
 super.onCaptureSuccess(image)

解决方法是,super.onCaptureSuccess(image)转换后必须调用。

原因可能是这个

/**
     * Returns the android {@link Image}.
     *
     * <p>If the ImageProxy is a wrapper for an android {@link Image}, it will return the
     * {@link Image}. It is possible for an ImageProxy to wrap something that isn't an
     * {@link Image}. If that's the case then it will return null.
     *
     * <p>The returned image should not be closed by the application. Instead it should be closed by
     * the ImageProxy, which happens, for example, on return from the {@link ImageAnalysis.Analyzer}
     * function.  Destroying the {@link ImageAnalysis} will close the underlying
     * {@link android.media.ImageReader}.  So an {@link Image} obtained with this method will behave
     * as such.
     *
     * @return the android image.
     * @see android.media.Image#close()
     */

推荐阅读