Android 如何将 ByteBuffer 转换成图像

How to convert ByteBuffer into image in Android

我正在通过套接字接收 jpg 图像,它作为 ByteBuffer 发送 我正在做的是:

        ByteBuffer receivedData ;
        // Image bytes
        byte[] imageBytes = new byte[0];
        // fill in received data buffer with data
        receivedData=  DecodeData.mReceivingBuffer;
        // Convert ByteByffer into bytes
        imageBytes = receivedData.array();
        //////////////
        // Show image
        //////////////
        final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
        showImage(bitmap1);

但是发生了什么,它无法解码 imageBytes 并且位图为空。

我还得到了 imagebytes 作为: 图像字节:{-1, -40, -1, -32, 0, 16, 74, 70, 73, 70, 0, 1, 1, 1, 0, 96, 0, 0, 0, 0, -1, -37、0、40、28、30、35、+10,478 更多}

会是什么问题? 是解码问题吗? 或从 ByteBuffer 到 Byte 数组的转换?

在此先感谢您的帮助。

ByteBuffer buf = DecodeData.mReceivingBuffer;
byte[] imageBytes= new byte[buf.remaining()];
buf.get(imageBytes);
final Bitmap bmp=BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
    showImage(bmp);

// Create a byte array
byte[] bytes = new byte[10];

// Wrap a byte array into a buffer
ByteBuffer buf = ByteBuffer.wrap(bytes);

// Retrieve bytes between the position and limit
// (see Putting Bytes into a ByteBuffer)
bytes = new byte[buf.remaining()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

// Retrieve all bytes in the buffer
buf.clear();
bytes = new byte[buf.capacity()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

最终位图 bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length); showImage(bmp);

使用上述任一方法将字节缓冲区转换为字节数组并将其转换为位图并将其设置到您的 IMAGEVIEW 中。

希望对您有所帮助。

这个对我有用(对于 ARGB_8888 像素缓冲区):

private Bitmap getBitmap(Buffer buffer, int width, int height) {
    buffer.rewind();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    return bitmap;
}