Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking screenshot in libgdx

I have an application in which i want to take the screenshot of the game screen and save it as an image and upload to Facebook. I am using Libgdx and my focus is android.

Can anyone help me that how to take screenshot of the game screen programmatically and save it as an image ??

like image 454
Ramiz Raja Avatar asked Dec 27 '22 17:12

Ramiz Raja


2 Answers

Simple solution:

Image screenShot = new Image(ScreenUtils.getFrameBufferTexture());
like image 20
Pascalius Avatar answered Jan 12 '23 15:01

Pascalius


It is now fairly easy. Libgdx provides an example, which can be found on the page Taking a Screenshot.

I had to add one statement to get it working. The image could not be saved directly to /screenshot1.png. Simply prepend Gdx.files.getLocalStoragePath().

Source Code:

public class ScreenshotFactory {

    private static int counter = 1;
    public static void saveScreenshot(){
        try{
            FileHandle fh;
            do{
                fh = new FileHandle(Gdx.files.getLocalStoragePath() + "screenshot" + counter++ + ".png");
            }while (fh.exists());
            Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
            PixmapIO.writePNG(fh, pixmap);
            pixmap.dispose();
        }catch (Exception e){           
        }
    }

    private static Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
        final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);

        if (yDown) {
            // Flip the pixmap upside down
            ByteBuffer pixels = pixmap.getPixels();
            int numBytes = w * h * 4;
            byte[] lines = new byte[numBytes];
            int numBytesPerLine = w * 4;
            for (int i = 0; i < h; i++) {
                pixels.position((h - i - 1) * numBytesPerLine);
                pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
            }
            pixels.clear();
            pixels.put(lines);
        }

        return pixmap;
    }
}
like image 88
Niklas Avatar answered Jan 12 '23 17:01

Niklas