dinsdag 19 januari 2016

Haxe / Stencyl : Exporting an image to PNG and optionally upload to online server

PHP Server code:

 * Server Side script:
$name = $_GET["name"];
foreach($_POST as $i){
    // If image is found 
    if(strlen($i) > 10) $img=$i;
file_put_contents("uploadDirectory/".$name, $img);
file_put_contents("uploadDirectory/debug.log", $debug , FILE_APPEND | LOCK_EX);


Stencyl Code Block (HaXe)  that uses an Image Attribute which will be stored on the server. In this code the Attribute is called Image

var _URL="http://_YourServer_/YourDirectory/AboveScript.php";

var UploadFile=“MyFile.png”;

// Call the encode function of the BitmapData which is the Image
var png = _Image.encode (_Image.rect, new openfl.display.PNGEncoderOptions());

// Get the bytes from the PNG file
var b = haxe.io.Bytes.alloc(png.length);
png.position = 0; 
var bytes:haxe.io.Bytes = haxe.io.Bytes.alloc(png.length);
while (png.bytesAvailable > 0) {
   var position = png.position;  
   bytes.set(position, png.readByte());

// You could save it to the local file system on Native (Windows/Mac) 

// In this case we upload the data to a website that has the above mentioned script.          

// bytes variable contains the data that we can send to the serve

var boundary:String = "-----------RANDOMTEXT_GENERATED";
var newline:String = "\r\n";
var str:String="";
var dat="";


var endje="";
endje=endje+"Content-Disposition: form-data; name=\"Upload\"\r\n\r\nSubmit Query\r\n"+boundary+"\r\n";

var req:URLRequest = new URLRequest(_URL+"?name=“+UploadFile));
req.requestHeaders=new Array<URLRequestHeader>();

var hdr:URLRequestHeader=new URLRequestHeader("Accept","*.png");

req.verbose = true;
req.method = URLRequestMethod.POST;


var ldr:URLLoader = new URLLoader(req);
// Probably not needed, but for large files it is nice to know when it is uploaded...
ldr.addEventListener(Event.COMPLETE, UploadDone);

For JPG/JPEG use JPEGEncoderOptions.

Geen opmerkingen:

Een reactie posten