OpenGL - 当尝试将字节数组转换为BufferedImage时,Image == null

时间:2014-03-30 22:20:07

标签: java image opengl byte jogl

我正在尝试使用glReadPixels()获取屏幕,然后将其转换为图像。 我得到一个错误,说image == null。

ByteBuffer _frame = ByteBuffer.allocate( 4 * Main.gui.glCanvas.getWidth() * Main.gui.glCanvas.getHeight() );
    System.out.println( "Num Pixels " + Main.width * Main.height );
    gl.glReadPixels(
            0,
            0,
            Main.gui.glCanvas.getWidth(),
            Main.gui.glCanvas.getHeight(),
            GL3.GL_RGBA,
            GL3.GL_UNSIGNED_BYTE,
            _frame
            );

    try {
        BufferedImage bi = ImageIO.read( new ByteArrayInputStream( _frame.array() ) );
        ImageIO.write( bi, "png", new File( "Slices/slicu.png" ) );
    } catch ( Exception e ) {
        System.out.println( e.getMessage() + " @ Filler.draw()" );
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:2)

而是使用com.jogamp.common.nio.Buffers.newDirectByteBuffer()而不是ByteBuffer.allocate()。如果你在这里使用一个非直接的NIO缓冲区,JOGL必须在底层制作一个直接的NIO缓冲区,你无法确定NIO缓冲区是否由数组支持,它可以为null。然后,创建一个数组并将缓冲区的内容复制到其中。

您可以使用com.jogamp.opengl.util.awt.Screenshotcom.jogamp.opengl.util.GLReadBufferUtilcom.jogamp.opengl.util.awt.AWTGLReadBufferUtil代替,在jogl-demos中有一些关于Github的示例。

我建议您在our official forum上提出有关JOGL的问题。