如何在Android中将ByteBuffer转换为图像

8

我通过socket接收到了一张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发送的,而是以字节流的形式发送的。 - greenapps
DecodeData.mReceivingBuffer. 你没有展示如何接收数据。代码非常不完整。请展示接收到的字节的十六进制表示,同时也请展示发送的字节的十六进制表示。 - greenapps
2个回答

16

这个对我有用(对于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;
}

9
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);

使用上述任意一种方法将 ByteBuffer 转换为字节数组,并将其转换为位图,然后将其设置到 ImageView 中。

希望这能帮到你。


1
仅有代码而没有进一步的解释并不是很有帮助。 - Robert
它使用 buf.get(imageBytes)不起作用;不要用数据填充 imagebytes。我认为 imageBytes = receivedData.array() 更好,现在正在解码但也无法显示,但还是谢谢。 - zelf
@Andolasoft 感谢你的帮助。我认为将 buf.get(imageBytes) 更改为 buf.array 的第一个解决方案会起作用,因为在这两个解决方案中,buf.get() 在 imageBytes 中没有写入任何内容。 - zelf
谢谢!BitmapFactory.decodeByteArray(buf, 0, buf.length)非常有用! - Trake Vital

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