Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ScreenUtils to save screenshot as image in libgdx

I am using ScreenUtils.getFrameBufferPixels(...) to take a screenshot of the game screen. I want to save the byte array returned by this method as an image in file. I am using libGDX and my focus in android.

like image 706
Ramiz Raja Avatar asked Sep 28 '12 17:09

Ramiz Raja


2 Answers

It is now fairly easy. Libgdx provides an example.

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 55
Niklas Avatar answered Sep 22 '22 17:09

Niklas


I had good luck with the minimal .PNG encoder provided by a libGDX forum member here: http://www.badlogicgames.com/forum/viewtopic.php?p=8358#p8358

Note that the resulting PNGs are not optimized, as the encoder is very simplistic (I used pngcrush offline to reduce their size dramatically).

I also had some problems with the alpha channel. The underlying screen color shows through transparent pixels on the screen, but does not come through in the pixels scraped off the screen (so this isn't really the fault of the PNG encoder). If your background is black, then just make sure the alpha channel is 1.0 in the pixels (unless you want the transparency in the screenshot, of course).

like image 29
P.T. Avatar answered Sep 20 '22 17:09

P.T.