java - 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 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 执行相同的操作,我不确定。

关于java - ByteBuffer 越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694298/

相关文章:

java - 使用泛型时复合模式的可扩展性

Java:newConstraints 不起作用

java - 如何正确填充 ArrayList<String> 类型的 ArrayList?

c# - 在 C# 中等效于 Java 的 "ByteBuffer.putType()"

java - 逐字节需要异或,但它显示为整数并丢失精度错误?

java - 具有以固定速率运行的可运行对象的 Java 项目可以在一段时间后停止吗?我的在大约 40 小时后仍然卡住

java - 如何在 GWT 标签中插入 <b> 元素

java - 如何在与Equal和hashcode一致的情况下实现compareTo()方法

java - 如果特定条件不成立,我可以什么都不返回

java - 从 ByteBuffer 读取前四个字节,然后将它们写回?