Search code examples
screenshotrgblwjgljavax.imageioglreadpixels

How to make a simple screenshot method using LWJGL?


So basically I was messing about with LWJGL for a while now, and I came to a sudden stop with with annoyances surrounding glReadPixels().
And why it will only read from left-bottom -> top-right.
So I am here to answer my own question since I figured all this stuff out,
And I am hoping my discoveries might be of some use to someone else.

As a side-note I am using:

glOrtho(0, WIDTH, 0 , HEIGHT, 1, -1);

Solution

  • So here it is my screen-capture code which can be implemented in any LWJGL application C:

    //=========================getScreenImage==================================//
        private void screenShot(){
                 //Creating an rbg array of total pixels
                 int[] pixels = new int[WIDTH * HEIGHT];
                 int bindex;
                 // allocate space for RBG pixels
                 ByteBuffer fb = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 3);
    
                 // grab a copy of the current frame contents as RGB
                 glReadPixels(0, 0, WIDTH, HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, fb);
    
                 BufferedImage imageIn = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
                 // convert RGB data in ByteBuffer to integer array
                 for (int i=0; i < pixels.length; i++) {
                     bindex = i * 3;
                     pixels[i] =
                         ((fb.get(bindex) << 16))  +
                         ((fb.get(bindex+1) << 8))  +
                         ((fb.get(bindex+2) << 0));
                 }
                 //Allocate colored pixel to buffered Image
                 imageIn.setRGB(0, 0, WIDTH, HEIGHT, pixels, 0 , WIDTH);
    
                 //Creating the transformation direction (horizontal)
                 AffineTransform at =  AffineTransform.getScaleInstance(1, -1);
                 at.translate(0, -imageIn.getHeight(null));
    
                 //Applying transformation
                 AffineTransformOp opRotated = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
                 BufferedImage imageOut = opRotated.filter(imageIn, null);
    
                 try {//Try to screate image, else show exception.
                     ImageIO.write(imageOut, format , fileLoc);
                 }
                 catch (Exception e) {
                     System.out.println("ScreenShot() exception: " +e);
                 }
             }
    

    I hope this has been useful.
    For any questions or comments on the code, ask/suggest as you like. C:
    Hugs,
    Rose.