在安卓中将byte[]渲染为位图

6

我从JNI调用中获得一个字节数组,并试图用它构建一个位图对象。

我的问题是,以下代码返回null。

    byte[] image = services.getImageBuffer(1024, 600);
    Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);

你有关于IT技术的任何提示吗?

PS:像素布局是BGR,而不是RGB。


你测试过图像字节数组是否包含正确的内容了吗?否则,你的代码看起来对我来说没问题。 - mreichelt
是的,我做到了。内容是正确的,只是decodeByteArray不理解。 - Marcos Vasconcelos
2个回答

4
文档中说此方法返回“如果无法解码图像,则为 null。”您可以尝试:
byte[] image = services.getImageBuffer(1024, 600);
InputStream is = new ByteArrayInputStream(image);
Bitmap bmp = BitmapFactory.decodeStream(is);

即使我认为这不会改变任何事情.. 但请尝试查看android.graphics.BitmapFactory.Options。

相同的错误。而且选项并不关心像素格式。 - Marcos Vasconcelos

1

decodeByteArray在这种格式下真的不起作用。我手动从BGR更改为RGB。

    byte[] image = services.getImageBuffer(1024, 600);

    Bitmap bmp = Bitmap.createBitmap(1024, 600, Bitmap.Config.RGB_565);
    int row = 0, col = 0;
    for (int i = 0; i < image.length; i += 3) {
        bmp.setPixel(col++, row, image[i + 2] & image[i + 1] & image[i]);

        if (col == 1024) {
            col = 0;
            row++;
        }

然而,

for (i < image.length) 。。。bmp.setPixel(image[i + 2] & image[i + 1] & image[i]); 

可能会导致:

08-29 14:34:23.460: ERROR/AndroidRuntime(8638): java.lang.ArrayIndexOutOfBoundsException


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接