Newbie question. I have a byte array (of total length 1920 X 1080 X 4), with every 4 bytes holding constant alpha value of 0x80 (~ 50% translucency) and RGB triplet, I would like to convert it to a bitmap using BitmapFactory. BitmapFactory always returns a null bitmap in the code below.
byte[] rgbImage; // allocated and populated with data elsewhere
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.outWidth = 1920;
opts.outHeight = 1080;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeByteArray(rgbImage, 0, 1920 * 1080 * 4, opts);
if(bitmap == null){
Log.e("TAG","bitmap is null");
}
What am I doing wrong? It seems that since any byte takes values in the range 0..255, even an arbitrary byte array would qualify as a RGB image, provided its dimensions made sense.
BitmapFactory.decodeByteArray doesn't accept unsupported formats, so, ensure that the rgbImage byte data is one of the supported image formats. Follow the link to see which ones:
https://developer.android.com/guide/topics/media/media-formats#image-formats
In addition, althouh not the cause of the failure, outWidth / outHeight are not meant to be populated by you, instead these are populated by BitmapFactory when inJustDecodeBounds is set to True in order to find out an image dimensions without decoding it. Setting them does nothing at all, as these are output parameters. Also note that when setting inJustDecodeBounds to True, the return value will be always Null, as the request becomes for the image dimensions and not the image itself.
Also note that for the length argument in decodeByteArray, you can pass rgbImage.length instead of 1920 * 1080 * 4, if such buffer has the same length.