Image to Bitmap conversion with MLKit returns null

127 Views Asked by At

I'm in Android and am trying to convert an object of type Image into Bitmap so to attach it to a Canvas object (Canvas takes bitmap). I convert to InputImage and then try to get bitmap out of it. But inputImage.getBitmapInternal() returns null. How can I fix it? And is there any ways to optimize this code? There is many conversions involved.

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));
2

There are 2 best solutions below

7
David Weber On

Use this method to convert the Drawable of your Image to a BitMap:

Image image = imageReader.acquireLatestImage();
Bitmap bitmap = convertDrawableToBitmap(image.getDrawable());

public Bitmap convertDrawableToBitmapNew(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

After that, you can draw it on a Canvas.

2
dev.bmax On

Images that the ImageReader reads can come in different formats (depending on who produces them). For example, video frames are typically encoded in the YCbCr color space (in Android it is usually referred to as YUV).

The Bitmap class on the other hand only supports RGB (currently).

This means, that your responsibility is to check the format of the image using image.getFormat() and convert the image if necessary.

The conversion of YUV to RGB, for example, is explained in this article.