【问题标题】:Java / OpenGL: Getting the image of a Canvas as a BufferedImageJava / OpenGL:将 Canvas 的图像作为 BufferedImage 获取
【发布时间】:2011-11-03 21:53:32
【问题描述】:

我有一些代码初始化 OpenGL 以呈现到 java.awt.Canvas。 问题是,我不知道如何获取画布的缓冲区并将其转换为 BufferedImage。

我尝试过覆盖 getGraphics()、克隆 Raster 并用自定义的 CanvasPeer 替换。

我猜 OpenGL 不会以任何方式使用 java 图形,那么我怎样才能获得 OpenGL 的缓冲区并将其转换为 BufferedImage?

我正在使用 LWJGL 的代码来设置父级:

Display.setParent(display_parent);
Display.create();

【问题讨论】:

  • 我也想知道这个问题的答案。

标签: java opengl graphics canvas lwjgl


【解决方案1】:

您需要从 OpenGL 缓冲区复制数据。我用的是这个方法:

FloatBuffer grabScreen(GL gl) 
{       
    int w = SCREENWITDH;
    int h = SCREENHEIGHT;
    FloatBuffer bufor = FloatBuffer.allocate(w*h*4); // 4 = rgba

    gl.glReadBuffer(GL.GL_FRONT);
    gl.glReadPixels(0, 0, w, h, GL.GL_RGBA, GL.GL_FLOAT, bufor); //Copy the image to the array imageData

    return bufor;
}

您需要根据您的 OpenGL 包装器使用类似的东西。这是 JOGL 示例。

这里是 LWJGL 包装器:

private static synchronized byte[] grabScreen()
{
    int w = screenWidth;
    int h = screenHeight;
    ByteBuffer bufor = BufferUtils.createByteBuffer(w * h * 3);

    GL11.glReadPixels(0, 0, w, h, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, bufor); //Copy the image to the array imageData

    byte[] byteimg = new byte[w * h * 3];
    bufor.get(byteimg, 0, byteimg.length);
    return byteimg;
}

编辑

这也可能有用(它不完全是我的,也应该调整):

BufferedImage toImage(byte[] data, int w, int h)
{
    if (data.length == 0)
        return null;

    DataBuffer buffer = new DataBufferByte(data, w * h);

    int pixelStride = 3; //assuming r, g, b, skip, r, g, b, skip...
    int scanlineStride = 3 * w; //no extra padding   
    int[] bandOffsets = { 0, 1, 2 }; //r, g, b
    WritableRaster raster = Raster.createInterleavedRaster(buffer, w, h, scanlineStride, pixelStride, bandOffsets,
            null);

    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    boolean hasAlpha = false;
    boolean isAlphaPremultiplied = true;
    int transparency = Transparency.TRANSLUCENT;
    int transferType = DataBuffer.TYPE_BYTE;
    ColorModel colorModel = new ComponentColorModel(colorSpace, hasAlpha, isAlphaPremultiplied, transparency,
            transferType);

    BufferedImage image = new BufferedImage(colorModel, raster, isAlphaPremultiplied, null);

    AffineTransform flip;
    AffineTransformOp op;
    flip = AffineTransform.getScaleInstance(1, -1);
    flip.translate(0, -image.getHeight());
    op = new AffineTransformOp(flip, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    image = op.filter(image, null);

    return image;
}

【讨论】:

    【解决方案2】:

    对于您的情况,我认为这是不可能的,原因如下:

    LWJGL 不会直接绘制到画布上(至少在 Windows 中不会)。画布仅用于获取窗口句柄以作为父窗口提供给 OpenGL。因此,画布永远不会被直接绘制到。要捕获内容,您可能不得不求助于屏幕捕获。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      相关资源
      最近更新 更多