Java如何将java.nio.Buffer转换为ByteBuffer

时间:2016-05-10 17:30:40

标签: java

我面临一个小问题我有两个库,一个发送输出为java.nio.Buffer,另一个接收输入为java.nio.ByteBuffer如何进行转换?

由于

缓冲区来自javaCV,来自这段代码:

private BytePointer[]   image_ptr;
private Buffer[]        image_buf;

// Determine required buffer size and allocate buffer
int size = avpicture_get_size(fmt, width, height);
image_ptr = new BytePointer[] { new BytePointer(av_malloc(size)).capacity(size) };
image_buf = new Buffer[] { image_ptr[0].asBuffer() };

// Assign appropriate parts of buffer to image planes in picture_rgb
// Note that picture_rgb is an AVFrame, but AVFrame is a superset of AVPicture
avpicture_fill(new AVPicture(picture_rgb), image_ptr[0], fmt, width, height);
picture_rgb.format(fmt);
picture_rgb.width(width);
picture_rgb.height(height);

1 个答案:

答案 0 :(得分:1)

首先,由于Buffer是一个抽象类,而ByteBuffer是它的子类之一,因此从第一个库获得的输出实际上可能是ByteBuffer。如果可能的话,检查库返回的Buffer的实现,因为如果它实际返回ByteBuffer,你可以将输出转换为ByteBuffer并完成。

如果你不知道库返回哪个Buffer实现,你将不得不求助于instanceof测试来确定它是什么子类,并在之后将返回的Buffer中的数据复制到新的ByteBuffer中。将它向下转换为子类。这是因为Buffer接口实际上并没有提供任何从缓冲区读取数据的方法;只有子类(ByteBuffer,ShortBuffer,LongBuffer等)才能做到。幸运的是,Buffer只有7个可能的子类,每个基本类型一个。

一旦确定了您拥有的Buffer的哪个子类,就可以使用this answer中描述的“asXXXBuffer()”方法将数据复制到ByteBuffer,如@Tunaki指出的那样。

代码看起来像这样:

Buffer outputBuffer = library.getBuffer();
ByteBuffer byteBuffer;
if (outputBuffer instanceof ByteBuffer) {
    byteBuffer = (ByteBuffer) outputBuffer;
} else if (outputBuffer instanceof CharBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity());
    byteBuffer.asCharBuffer().put((CharBuffer) outputBuffer);
} else if (outputBuffer instanceof ShortBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity() * 2);
    byteBuffer.asShortBuffer().put((ShortBuffer) outputBuffer);
} else if (outputBuffer instanceof IntBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity() * 4);
    byteBuffer.asIntBuffer().put((IntBuffer) outputBuffer);
} else if (outputBuffer instanceof LongBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity() * 8);
    byteBuffer.asLongBuffer().put((LongBuffer) outputBuffer);
} else if (outputBuffer instanceof FloatBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity() * 4);
    byteBuffer.asFloatBuffer().put((FloatBuffer) outputBuffer);
} else if (outputBuffer instanceof DoubleBuffer) {
    byteBuffer = ByteBuffer.allocate(outputBuffer.capacity() * 8);
    byteBuffer.asDoubleBuffer().put((DoubleBuffer) outputBuffer);
} 

请注意,您分配的ByteBuffer的大小取决于您要复制的Buffer的哪个子类,因为使用不同的字节数存储不同的基元类型。例如,由于int是4个字节,如果您的库为您提供IntBuffer,则需要分配容量为4倍的ByteBuffer。

相关问题