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 ??
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With