Reputation: 51
First time asking a question here so sorry if I do something wrong.
I’m using Haxeflixel (compiling to c++) and I’ve been trying to figure out how I can encode and save a BitmapData as a PNG to a file without any kind of dialog like the sys.FileSystem.saveContent and sys.FileSystem.saveBytes functions, but every method I try either isn’t valid and won’t compile or creates an invalid PNG that can’t be read as an image at all.
Currently this is basically what I have:
function saveBitmap(image:BitmapData)
{
var bytes:ByteArray = PNGEncoder.encode(image);
sys.FileSystem.saveBytes("assets/images/Encoded Image.png", bytes);
}
This code compiles and runs just fine but the PNG image created isn’t valid
Can anyone explain why this doesn’t work and how I make it actually work as I’ve been trying to figure this out for far too long.
Upvotes: 1
Views: 329
Reputation: 51
i've managed to make it work using
var bytes:ByteArray = image.encode(image.rect, new PNGEncoderOptions);
instead of
var bytes:ByteArray = PNGEncoder.encode(image);
i guess either PNGEncoder doesnt work or i was using it wrong
edit: the images created can be read by everything i've tried exept Haxeflxiel itself for some reason, i've tried different BitmapData's made from different methods but it's still the same, could use help with that too.
Upvotes: 1
Reputation: 386
Just FYI, if you are compiling to JavaScript you won’t have access to the file system class. See the “targets” list on this page. So I am assuming you are building to html5.
I am currently working on a project for JavaScript target which requires JSON file download (a text format). I'm using an external JS library called FileSaver for that, plus the Filesaver extern from haxelib (requires installation first). It requires that you convert your data to a "blob" first. My code is doing a text file but in your case you need to generate a PNG, so you probably need to pass your ByteArray to the Blob constructor. Something like this:
var bytes:ByteArray = PNGEncoder.encode(image);
var blob = new Blob([bytes],{type: "image/png"});
var fileName = "myImage.png";
FileSaver.saveAs(blob, fileName);
In your project.xml you will need this line:
<haxelib name="FileSaver"/>
and in your html you need the library:
<script type="text/javascript" src="./js/FileSaver.min.js"></script>
I didn't test it but that's the direction I would go for HTML5.
Upvotes: 0