How would I save a file with a openfl sprite's pixels? (With rectangle ofc)

I’m trying to make it so that I can screenshots only the openfl sprite with rectangle clipping and not the whole application screen. How would I do that?

You can use the BitmapData’s class draw method (openfl.display.BitmapData - API Reference). Create the bitmapdata object with the size and background color you want and draw your sprite into it (you may use the method’s Matrix parameter to adjust position if needed). Then you can use the encode method (openfl.display.BitmapData - API Reference) to generate your picture.

1 Like

I took code from extension-screenshot but for some reason it doesn’t work. It actually saves an unreadable image file.

I did use FlxG.game which is actually a openfl sprite

Try something like this:

import openfl.text.TextField;
import openfl.display.BitmapData;
import haxe.io.Bytes;
import haxe.crypto.Base64;
import js.Browser;


//then in your class:
var tf = new TextField();
tf.cacheAsBitmap = true;
tf.text = "Hello World";
var bmd = new BitmapData(100,30);
bmd.draw(tf); //in your case use a Sprite instead of this textfield. Any display object should work

//if you want a Rectangle like you mentioned, pass it to the draw function:
//draw(source:IBitmapDrawable, ?matrix:Matrix, ?colorTransform:ColorTransform, ?blendMode:BlendMode, ?clipRect:Rectangle, smoothing:Bool = false):Void

var imageData:Bytes = bmd.image.encode(ImageFileFormat.JPEG,60);
var b64 = Base64.encode(imageData);

untyped {
var link = js.Browser.document.createElement('a');
link.download = "myimage.jpg";
link.href = "data:"+"application/octet-stream"+";base64,"+b64;
link.click();
}

If you’re not in html5 target it would be more like:


import sys.io.*;
import sys.FileSystem;

var fileBytes = Base64.decode(b64);
var fileName = '/workspace/exports/myimage.jpg';
if(!FileSystem.exists('/workspace/exports/')) FileSystem.createDirectory('/workspace/exports/');
File.saveBytes(fileName,fileBytes);

I haven’t tested this, just assembled it from some code I had on hand.