【问题标题】:ByteBuffer to byte arrayByteBuffer 到字节数组
【发布时间】:2015-03-09 10:50:49
【问题描述】:

我有一个 ByteBuffer,我需要将其内容添加到 POST 请求中,以便远程显示代表的图像;但我不知道该怎么做。

这样做是行不通的:

byteBuffer.array()

我尝试将其转换为字节数组,但由于图像显示不正确,因此无法正常工作:

byte[] byteArray = new byte[byteBuffer.remaining()];
frame.duplicate().get(byteArray);
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new ByteArrayEntity(byteArray));

我也考虑过将其转换为图像并获取其字节数组,但我不知道该怎么做以及它是否可以工作......

任何帮助将不胜感激。

【问题讨论】:

  • byteBuffer.array() 不起作用?这是一个很好的主张。
  • 不,byteBuffer.array() 不能正确形成图像,如果我调试应用程序,这样做的结果是一个数组,其中每个元素都是 0 值...
  • 那么要么你没有读到任何东西,要么你没有调试过。
  • @svprdga 向我们展示如何填充字节缓冲区。很有可能,错误就在那里。
  • @EJP:来自 ByteBuffer.array() 的文档:“返回此缓冲区所基于的字节数组,如果有的话”,也许我的 ByteBuffer 是以其他方式制作的。 ...??

标签: java bytearray bytebuffer


【解决方案1】:
private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
    byte[] bytesArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytesArray, 0, bytesArray.length);
    return bytesArray;
}

【讨论】:

    【解决方案2】:

    使用allocate(不一定是allocateDirect)创建的ByteBuffer 应该有一个后备数组,请检查hasArray() / isDirect()

    byteBuffer.flip();  // Sets limit to current write position.
    int n = byteBuffer.limit();
    byteBuffer.rewind(); // Already done by flip I think.
    byte[] data = new byte[n];
    byteBuffer.get(data);
    

    【讨论】:

    • hasArray() 返回 false。我试过你的代码,byteBuffer.limit() 返回 0,最终数据数组的长度为 0...
    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 2010-10-15
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2013-05-28
    • 2023-03-05
    • 2016-04-03
    相关资源
    最近更新 更多