首先是BufferOverFlowException .put()

时间:2015-01-27 02:14:01

标签: java opengl buffer lwjgl

由于之前没有翻转缓冲区我遇到了问题,但现在我无法使用.put()或.putInt()来添加缓冲区,它会在第一次尝试时不断抛出BufferOverflowException:

buffer.put((byte) c.getRed());

以下相关代码:

BufferedImage image = loadImage(".\\res\\" + fileName);
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());

ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
buffer.flip();
Color c;

for (int y = 0; y < image.getHeight(); y++) {
    for (int x = 0; x < image.getWidth(); x++) {
        c = new Color(image.getRGB(x, y));
        buffer.put((byte) c.getRed());     // Red component
        buffer.put((byte) c.getGreen());      // Green component
        buffer.put((byte) c.getBlue());               // Blue component
        buffer.put((byte) c.getAlpha());    // Alpha component. Only for RGBA
    }
}

1 个答案:

答案 0 :(得分:2)

您对buffer.flip()的来电是错误的。来自documentation

  

翻转此缓冲区。限制设置为当前位置,然后将位置设置为零。

其中 limit 定义为:

  

缓冲区的限制是不应读取或写入的第一个元素的索引。缓冲区的限制永远不会为负,并且永远不会超过其容量。

由于在分配缓冲区后立即调用flip(),当前位置为0,flip()调用将限制设置为0.这意味着在索引0或之后无法写入任何内容它。这反过来意味着根本不能写任何东西。

要解决此问题,您需要在使用buffer.flip()的值填充缓冲区的循环之后移动buffer.put()调用

原始代码丢失的要点是在向其写入数据后需要将缓冲区位置设置为0。否则,将来的操作将在当前位置开始读取,这是您完成所有buffer.put()操作后缓冲区的结束。

在用数据填充缓冲区后,有多种方法可以将位置重置为0。其中任何一个都应该完成这项工作:

buffer.flip();
buffer.position(0);
buffer.rewind();