Java ByteBuffer越界异常

Java ByteBuffer越界异常,java,indexoutofboundsexception,bytebuffer,Java,Indexoutofboundsexception,Bytebuffer,我有一个ByteBuffer,其中存储了任意尺寸的RGBA图像。我试图用一个单一的、随机的、RGBA颜色的三角形覆盖图像的某些部分。然而,我有一个IndexOutOfBoundsException,这对我来说毫无意义 public ByteBuffer getByteBuffer() { /*Creates a ByteBuffer containing an image of a single background colour. A single pixel in the image

我有一个ByteBuffer,其中存储了任意尺寸的RGBA图像。我试图用一个单一的、随机的、RGBA颜色的三角形覆盖图像的某些部分。然而,我有一个IndexOutOfBoundsException,这对我来说毫无意义

public ByteBuffer getByteBuffer()
{
    /*Creates a ByteBuffer containing an image of a single background colour. A single pixel in the image is
    represented as a float array of size 4*/
    ByteBuffer buffer = Helpers.getBGByteBuffer(new float[]{1f, 1f, 1f, 1f}, width * height * 4 * Float.BYTES);
    ByteBuffer triBuffer;
    int        offset;

    for(RenderTriangle triangle : triangleList)
    {
        offset = triangle.getOffset().y; //Indicates the offset (position) of the triangle in relation to the image
        triBuffer = triangle.getByteBuffer(); //Gets the ByteBuffer of the triangle.

        for(int i = 0; i < triBuffer.capacity(); i += 4 * Float.BYTES) //Float.BYTES = 4
        {
            byte[] rgba1 = new byte[4 * Float.BYTES];
            byte[] rgba2 = new byte[4 * Float.BYTES];

            triBuffer.get(rgba1, i, rgba1.length); //Throws exception for i = 16
            buffer.get(rgba2, offset + i, rgba2.length);

            byte[] rgbaAdded = Helpers.addBytesAsFloats(rgba1, rgba2); //Calculates resulting RGBA value

            buffer = buffer.put(rgbaAdded, offset + i, rgbaAdded.length);
        }
    }
    return buffer;
}
在引发异常之前的第二次迭代中的一些相关调试值:

offset = 0 
i = 16
rgba1 = {byte[16]@xxx}
rgba2 = {byte[16]@xxx}
triBuffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=16 lim=64 cap=64]"
buffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=32 lim=64 cap=64]"

我认为这句话是不对的

由于ByteBuffer是一个缓冲区,它使用自己的索引来跟踪它所在的位置,因此当您读取16个字节时,下次读取时,您将读取下一个16个字节(不返回到开头)

在您的行中,
i
参数实际上代表要插入的目标数组的位置

所以我认为正确的行应该是:
tribbfer.get(rgba1,0,rgba1.length)


也许你需要对另一个ByteBuffer做同样的事情,我不确定。

我认为这句话是错误的

由于ByteBuffer是一个缓冲区,它使用自己的索引来跟踪它所在的位置,因此当您读取16个字节时,下次读取时,您将读取下一个16个字节(不返回到开头)

在您的行中,
i
参数实际上代表要插入的目标数组的位置

所以我认为正确的行应该是:
tribbfer.get(rgba1,0,rgba1.length)


也许你需要对另一个ByteBuffer执行同样的操作,我不确定。

这确实是问题所在,我还必须在每次get操作后倒回
buffer
16字节,以说明读取后缓冲区位置的移动。这确实是问题所在,我还必须在每次get操作后倒回
buffer
16字节,以说明从中读取后缓冲区位置的移动。
offset = 0 
i = 16
rgba1 = {byte[16]@xxx}
rgba2 = {byte[16]@xxx}
triBuffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=16 lim=64 cap=64]"
buffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=32 lim=64 cap=64]"