使用 MLKit 进行图像到位图转换返回 null

问题描述 投票:0回答:1

我在 Android 中,正在尝试将

Image
类型的对象转换为
Bitmap
,以便将其附加到
Canvas
对象(画布采用位图)。我转换为 InputImage 然后尝试从中获取位图。但是
inputImage.getBitmapInternal()
返回 null。我该如何修复它?有什么方法可以优化这段代码吗?涉及很多转换。

Image image = imageReader.acquireLatestImage();
        
InputImage inputImage = InputImage.fromMediaImage(image, rotation);
Bitmap bitmap= inputImage.getBitmapInternal();
//.... 
canvas.drawBitmap(bitmap, 0, 0, new Paint(Paint.ANTI_ALIAS_FLAG));
java android android-canvas google-mlkit image-reader
1个回答
0
投票

你可以试试这个:

InputImage inputImage = // Your InputImage instance

// Get the ByteBuffer from the InputImage
ByteBuffer buffer = inputImage.getByteBuffer();

// Create a Bitmap from the ByteBuffer
Bitmap bitmap = Bitmap.createBitmap(
        inputImage.getWidth(),
        inputImage.getHeight(),
        Bitmap.Config.ARGB_8888
);

// Copy the buffer data into the Bitmap
buffer.rewind(); // Ensure the buffer is at the beginning
bitmap.copyPixelsFromBuffer(buffer);

// Now, 'bitmap' contains the image data from the InputImage
© www.soinside.com 2019 - 2024. All rights reserved.