BitmapFactory returns ARGB 字节数组的空位图 (Android)

BitmapFactory returns null bitmap for ARGB byte array (Android)

新手问题。我有一个字节数组(总长度为 1920 X 1080 X 4),每 4 个字节保持恒定的 alpha 值 0x80(~ 50% 半透明度)和 RGB 三元组,我想使用 BitmapFactory 将其转换为位图。 BitmapFactory 在下面的代码中总是 returns 空位图。

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");
}

我做错了什么?似乎由于任何字节都采用 0..255 范围内的值,所以即使是任意字节数组也可以作为 RGB 图像,只要它的尺寸有意义。

BitmapFactory.decodeByteArray 不接受不受支持的格式,因此,请确保 rgbImage 字节数据 是受支持的图像格式之一 。按照link查看有哪些:

https://developer.android.com/guide/topics/media/media-formats#image-formats

此外,虽然不是失败的原因,但 outWidth / outHeight 并不是要由您填充,而是这些当 inJustDecodeBounds 设置为 True 时,由 BitmapFactory 填充,以便在不解码的情况下找出图像尺寸。设置它们根本没有任何作用,因为这些是输出参数。另请注意,当将 inJustDecodeBounds 设置为 True 时,return 值将始终为 Null,因为请求变成了图像尺寸而不是图像本身。

另请注意,对于 decodeByteArray 中的 length 参数,您可以传递 rgbImage.length 而不是 1920 * 1080 * 4,如果此类缓冲区具有相同的长度。