BitmapFactory.decodeByteArray() 始终 returns null(手动创建的字节数组)

BitmapFactory.decodeByteArray() always returns null (manually-created byte array)

所以我正在尝试从一位通过蓝牙串行端口获取图像数据的同事那里移植一些 C++ 代码(我正在使用 Android phone)。我需要根据数据生成位图。

在测试移植的代码之前,我写了这个快速函数来假设生成一个纯红色的矩形。但是,BitmapFactory.decodeByteArray() 总是失败并且 returns 带有空位图。我已经检查了它可能抛出的两种可能的异常,但都没有抛出。

byte[] pixelData = new byte[225*160*4];
                for(int i = 0; i < 225*160; i++) {
                    pixelData[i * 4 + 0] = (byte)255;
                    pixelData[i * 4 + 1] = (byte)255;
                    pixelData[i * 4 + 2] = (byte)0;
                    pixelData[i * 4 + 3] = (byte)0;
                }
                Bitmap image = null;
                logBox.append("Creating bitmap from pixel data...\n");
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                options.outWidth = 225;
                options.outHeight = 160;

                try {
                    image = BitmapFactory.decodeByteArray(pixelData, 0, pixelData.length, options);
                } catch (IllegalArgumentException e) {
                    logBox.append(e.toString() + '\n');
                }
                //pixelData = null;
                logBox.append("Bitmap generation complete\n");

decodeByteArray() 代码:

public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
    if ((offset | length) < 0 || data.length < offset + length) {
        throw new ArrayIndexOutOfBoundsException();
    }

    Bitmap bm;

    Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "decodeBitmap");
    try {
        bm = nativeDecodeByteArray(data, offset, length, opts);

        if (bm == null && opts != null && opts.inBitmap != null) {
            throw new IllegalArgumentException("Problem decoding into existing bitmap");
        }
        setDensityFromOptions(bm, opts);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
    }

    return bm;
}

我认为是 nativeDecodeByteArray() 失败了。

我还注意到日志消息:

D/skia: --- SkImageDecoder::Factory returned null

有人有什么想法吗?

BitmapFactory

decodeByteArray 实际上 解码 图像,即以 JPEG 或 PNG 等格式编码的图像。 decodeFiledecodeStream 更有意义,因为您的编码图像可能来自文件或服务器或其他东西。

您不想解码任何内容。您正在尝试将原始图像数据转换为位图。查看您的代码,您似乎正在生成一个 225 x 160 位图,每个像素 4 个字节,格式化为 ARGB。所以这段代码应该适合你:

    int width = 225;
    int height = 160;
    int size = width * height;
    int[] pixelData = new int[size];
    for (int i = 0; i < size; i++) {
        // pack 4 bytes into int for ARGB_8888
        pixelData[i] = ((0xFF & (byte)255) << 24) // alpha, 8 bits
                | ((0xFF & (byte)255) << 16)      // red, 8 bits
                | ((0xFF & (byte)0) << 8)         // green, 8 bits
                | (0xFF & (byte)0);               // blue, 8 bits
    }

    Bitmap image = Bitmap.createBitmap(pixelData, width, height, Bitmap.Config.ARGB_8888);