【问题标题】:How to convert ByteBuffer into image in Android如何在 Android 中将 ByteBuffer 转换为图像
【发布时间】:2016-12-03 00:38:51
【问题描述】:

我通过套接字接收 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 数组?

提前感谢您的帮助。

【问题讨论】:

  • it is sent as ByteBuffer。不要这么想。它以字节流的形式发送。
  • DecodeData.mReceivingBuffer。你没有说明你是如何收到数据的。非常不完整的代码。请显示接收字节的十六进制表示法。请发送十六进制字节。

标签: android image bitmap bytearray bytebuffer


【解决方案1】:
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); 显示图像(bmp);

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

希望这会对你有所帮助。

【讨论】:

  • 只是代码没有任何进一步的解释不是很有帮助。
  • 它无法使用 buf.get(imageBytes);不要用我认为的数据填充图像字节 imageBytes = receivedData.array();好多了,现在正在解码但也无法显示,但是谢谢
  • @Andolaso​​ft 感谢您的帮助我认为第一个解决方案是更改 buf.get(imageBytes);到 buf.array 将起作用,因为 buf.get() 在两个解决方案中的 imageBytes 内什么都不写。
  • 谢谢! BitmapFactory.decodeByteArray(buf, 0, buf.length) 真的很有用!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-27
    • 2020-11-24
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多