I'm making a game in which I need to export a texture which the user has edited as a .png into a specified location. I'd like it if I could have the default saving window thing (like on other apps when you do cmd+s). If this isn't possible, is there any way in GDX to export a texture (as a .png) to the computer (and preferably not the assets folder)
1 Answer
One way of achieving this would be to save the portion of the screen where they've made their edits by taking a screen shot using the ScreenUtils.getFrameBufferPixmap
method and then dumping the Pixmap
data to a file using the PixmapIO
class that can write PNGs from a Pixmap
.
public class ScreenshotFactory {
private static int counter = 1;
public static void saveScreenshot(){
try{
FileHandle fh;
do{
fh = new FileHandle("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);
pixels.clear();
}
return pixmap;
}
}
The snippet above is snagged from Take a Screenshot for libGDX on github. It should be easy to modify it to take only a portion of the screen or to change it to work on a Pixmap
grabbed from another FrameBuffer
.
-
\$\begingroup\$ But how would I export this to anywhere on the computer, not just assets, for example onto the desktop. \$\endgroup\$– Zac GJan 10, 2016 at 15:16
-
\$\begingroup\$ Use the following path with the FileHandle: System.getProperty("user.home") + "/Desktop/picname.png" , but keep in mind that this is not guaranteed to work in every case. There are already separate questions debating this topic on stackexchange, just search a bit! \$\endgroup\$ Jan 10, 2016 at 17:57
-
\$\begingroup\$ The constructor I've used on the
FileHandle
class is the one that sets the type of file toAbsolute
, this means you can specify a full path to a folder anywhere on your machine. It won't be portable beyond the Desktop version, but I guess that's not something you care about in this case. \$\endgroup\$ Jan 11, 2016 at 7:58