Saving an image in Android pictures directory

Hello everyone,

I’m working in a little game with HaxeFlixel and I was wondering how to make a screenshot and save it in the pictures Android directory.

So far I got:

private function screenshot():Void
	{
		var region:Rectangle;
		region = new Rectangle( 0, 0, FlxG.width, FlxG.height );
		var theBitmap:Bitmap = new Bitmap( new BitmapData( Std.int( region.width ), Std.int( region.height ), true, 0x0 ) );
		var m:Matrix = new Matrix( 1, 0, 0, 1, -region.x, -region.y );
		theBitmap.bitmapData.draw( FlxG.stage, m );
		
		var png:ByteArray = PNGEncoder.encode( theBitmap.bitmapData );
		var file:FileReference = new FileReference();
		var filename = "screenshot.png";
		
		file.save( png, filename );
	}

First I was wondering if my way to make a screenshot seems ok, and second I got no clue how to save the image in a directory in Android where I could look at it.

If the bitmap looks accurate, then I would say to keep your code up until the point that you get a ByteArray.

Then you’ll want a combination of lime.system.System.documentsDirectory (or maybe it’s userDirectory or desktopDirectory) to get a path for external storage. Then I think most phones have a DCIM directory for the camera, but there may be other folders for downloads or other pictures.

You’ll then want a combination of sys APIs for working with directories or files, such as sys.FileSystem or sys.io.File, like:

var path = System.documentsDirectory + "/Photos";
if (!FileSystem.exists (path)) {
    FileSystem.mkdir (path);
}
path += "/Screenshot_" + ID + ".png";
File.saveBytes (path, png);

You may also want to consider JPEG encoding, since screenshots probably will not have transparency

Thanks for your quick reply!

I gave a try with System.documentsDirectory but it crash!
(Got no crash if I use System.applicationStorageDirectory or System.applicationDirectory)

I read that some people got problems because of hxcpp, perhaps I should look on that way too.

Or maybe it’s my use of ByteArray, not sure how to be sure I get it good or not!

Also, be aware that the directory might not exist, yet. You might actually have to FileSystem.exists (System.documentsDirectory) or mkdir