Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 首先是BufferOverFlowException.put()_Java_Opengl_Buffer_Lwjgl - Fatal编程技术网

Java 首先是BufferOverFlowException.put()

Java 首先是BufferOverFlowException.put(),java,opengl,buffer,lwjgl,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()]

由于以前没有翻转缓冲区,我遇到了一个问题,但现在我无法让缓冲区添加任何带有.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
    }
}
buffereImage=loadImage(“.\\res\\”+文件名);
int[]像素=新的int[image.getWidth()*image.getHeight()];
getRGB(0,0,image.getWidth(),image.getHeight(),pixels,0,image.getWidth());
ByteBuffer buffer=BufferUtils.createByteBuffer(image.getWidth()*image.getHeight()*4);
flip();
颜色c;
对于(int y=0;y
buffer.flip()的调用位于错误的位置。从:

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

其中,限制定义为:

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

由于在分配缓冲区后立即调用
flip()
,当前位置为0,因此
flip()
调用将限制设置为0。这意味着在索引0处或之后不能写入任何内容。这就意味着什么也写不出来

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

原始代码缺少的主要一点是,在将数据写入缓冲区后,需要将缓冲区位置设置为0。否则,将来的操作将从当前位置开始读取,即完成所有
buffer.put()操作后缓冲区的末尾

在用数据填充缓冲区后,有多种方法将位置重置为0。其中任何一项都应起作用:

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

让我们看看
BufferUtils#createByteBuffer
做了什么。与您的
ByteBuffer
问题无关,为什么您要用rgb值填充
int[]
,然后循环通过x,y坐标并分别获得每个rgb值?BufferUtils的Javadoc页面:同样对于上面的注释,我这样做是因为int[]持有一个我需要使用位掩码来获取红色、绿色和蓝色组件的值,因此我认为简单地执行上面的方法比执行此问题中的第二条注释解释的内容更容易:。