Screenshots are easy in LibGDX!

Post processing to guarantee clarity

This will guarantee your screenshots look like just like what the user expects:

  1. byte[] pixels = ScreenUtils.getFrameBufferPixels(0, 0, Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), true);
  2. // This loop makes sure the whole screenshot is opaque and looks exactly like what the user is seeing
  3. for (int i = 4; i <= pixels.length; i += 4) {
  4. pixels[i - 1] = (byte) 255;
  5. }
  6. Pixmap pixmap = new Pixmap(Gdx.graphics.getBackBufferWidth(), Gdx.graphics.getBackBufferHeight(), Pixmap.Format.RGBA8888);
  7. BufferUtils.copy(pixels, 0, pixmap.getPixels(), pixels.length);
  8. PixmapIO.writePNG(Gdx.files.external("mypixmap.png"), pixmap);
  9. pixmap.dispose();

No post-processing

If you have no layered transparency, here’s a more compact and efficient way:

  1. Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
  2. PixmapIO.writePNG(Gdx.files.external("mypixmap.png"), pixmap, Deflater.DEFAULT_COMPRESSION, true);
  3. pixmap.dispose();