using ScreenUtils to save screenshot as image in libgdx

有些话、适合烂在心里 提交于 2019-12-12 08:11:53

问题


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.


回答1:


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;
    }
}



回答2:


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).



来源:https://stackoverflow.com/questions/12644733/using-screenutils-to-save-screenshot-as-image-in-libgdx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!