ByteBuffer 越界异常

ByteBuffer out of bounds exception

我有一个 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;
}

以上代码在

的 for 循环的第二次迭代(因此 i = 16)中抛出异常
triBuffer.get(rgba1, i, rgba1.length),

第二次迭代时的一些相关调试值,就在抛出异常之前:

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 参数实际上代表要插入的目标数组的位置。

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

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