use as3 NativeProcess to run windows cmd - actionscript-3

I used the NativeProcess to run my .cmd file to use the convert of Imagemagick on Windows.
the cmd is
convert -resize 1%x2% 3% 4%
On my computer,it looked normal.
But on some other computer,the bug looked like the “-resize” was be garbled.
then I changed the cmd
convert 1% 2%x3% 4% 5%
but on some computer,it still have the bug.
Is that the air output UTF-8,and the windows CMD use Unicode?
How to use it will not produce this error?
my code is
private var mProcess:NativeProcess;
private function convertImgToTargetPng(filePath:String,resultFilePath:String,width:Number,height:Number,scale:Number=1):void
{
var convertFile:File = File.applicationDirectory.resolvePath("script").resolvePath("convert.cmd");
var nativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.executable = convertFile;
nativeProcessStartupInfo.workingDirectory = File.userDirectory;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("-resize");
processArgs.push(width*scale);
processArgs.push(height*scale);
processArgs.push(filePath);
processArgs.push(resultFilePath);
nativeProcessStartupInfo.arguments = processArgs;
mProcess = new NativeProcess();
mProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onConvertErrorHandler);
mProcess.addEventListener(NativeProcessExitEvent.EXIT, onConvertExitHandler);
try
{
mProcess.start(nativeProcessStartupInfo);
}
catch (e : Error)
{
Alert.show("convert failed: " + e.message);
}
}
private function onConvertErrorHandler(event : ProgressEvent):void
{
var data:String = mProcess.standardError.readUTFBytes(mProcess.standardError.bytesAvailable);
Alert.show("convert error :" + data);
}
private function onConvertExitHandler(event : NativeProcessExitEvent):void
{
mProcess.removeEventListener(ProgressEvent.STANDARD_ERROR_DATA, onConvertErrorHandler);
mProcess.removeEventListener(NativeProcessExitEvent.EXIT, onConvertExitHandler);
Alert.show("convert success");
}

Untested but you can try...
Make a changed CMD file that looks like: convert 1% 2% 3% 4%
and update your AS3 code section to look like this...
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("-resize");
processArgs.push(String ( String(width*scale) + "x" + String(height*scale) ) );
processArgs.push(filePath);
processArgs.push(resultFilePath);
Let me now how it goes.
Also instead of a .cmd file, why not just run the process with convert.exe file itself? :
If that convert.exe is located here : c:\program files\imagemagick\convert.exe Then use path location in AS3 code as c:\\program files\\imagemagick\\convert.exe
private function convertImgToTargetPng(filePath:String,resultFilePath:String,width:Number,height:Number,scale:Number=1):void
{
//# Use your location of convert.exe
var convertFile : File = new File("C:\\imageMagick\\converter.exe");
if ( convertFile.exists ) //# If found in your location
{
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo(); //vc
nativeProcessStartupInfo.executable = convertFile;
nativeProcessStartupInfo.workingDirectory = File.userDirectory;
var processArgs:Vector.<String> = new Vector.<String>();
processArgs.push("-resize");
processArgs.push(String ( String(width*scale) + "x" + String(height*scale) ) );
processArgs.push(filePath);
processArgs.push(resultFilePath);
nativeProcessStartupInfo.arguments = processArgs;
mProcess = new NativeProcess();
mProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onConvertErrorHandler);
mProcess.addEventListener(NativeProcessExitEvent.EXIT, onConvertExitHandler);
try { mProcess.start(nativeProcessStartupInfo); }
catch (e : Error)
{ Alert.show("convert failed: " + e.message); }
}
}

Related

Firebase "MD5" & BloddyCrytpo's dont match

I'm trying to do a check to see if the user has a local file. If the user does, I get bloodycrypto to make a md5 out of it. Then I compare the two values. One from the firebase file's metadata and the other from the byte array of the file digested. They never match. Does Firebase do something different when trying to generate the md5 of a file I upload?
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA)
trace("Local hash = " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("Network hash = " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
if (byteHash != storageMetaData.md5Hash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
Upon closer inspetion (thanks to Organis) firebase doesn't return a proper MD5. What is it? In my storage consol I don't see an md5 property, so is this autogenerated? The files were uploaded through my rest API based off phantom's guide.
Update: Following Organis' comment about the way Firebase handle's MD5s
var byteHash:ByteArray = new ByteArray();
byteHash.writeUTFBytes(MD5.hashBytes(fileBA));
var byteHashWithLength:ByteArray = new ByteArray();
byteHashWithLength.writeUTF(MD5.hashBytes(fileBA));
trace("Bytehash with length = " + Base64.encode(byteHashWithLength)); //ACAyMTMzYTdmYjczYTEzZDQ3ZDkzMTEyY2I1OWQyYTBmMg==
trace("Plain = " + Base64.encode(byteHash)); //OTNiODg1YWRmZTBkYTA4OWNkZjYzNDkwNGZkNTlmNzE=
trace("Storage md5 = " + storageMetaData.md5Hash); //UsoNl5sL1+aLiAhTOTBXyQ==
Trying to take the md5 I get and turn it into base64 results in consistent mismatching results. Is there an argument I am missing or applying incorrectly when I try to decode everything?
...So I would do something like
var storageHash:String = Base64.decode(storageMetaData.md5Hash).toString();
to follow your example right?
Try this code below to get your storageMetaData.md5Hash correctly decoded from Base64 :
Let me know result of trace("storage hash : " + storageHash); to check if you're getting an (expected) sequence of 32 hex values.
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA); //Local hash
var ba_storageHash:ByteArray = new ByteArray();
ba_storageHash = Base64.decode(storageMetaData.md5Hash); //update ByteArray
var storageHash:String = bytesToHexString(ba_storageHash); //Hex values of bytes shown as String
trace("Network hash : " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
trace("Local hash : " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("storage hash : " + storageHash); //what is result??
if (byteHash != storageHash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
// # Byte values (Hex) shown as (returned) String type
private function bytesToHexString(input:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
input.position = 0;
var intBASize:uint = input.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = input.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toLowerCase(); //strOut.toUpperCase();
}

How to get byteArray or base64 string from RenderTexture Cocos2d-JS

I am making a game on cocos2d-JS for facebook in which there is a requirement of sharing a screenshot of the game.
I am able to take the screenshot but now I am unable to upload it in the Parse.com server because it requires base64 format or byte array. I am unable to find any solution of converting Sprite in to this format.. Here's my code so result when I do addchild its coming proper .. I have also added my commented code so that it will help to understand that I have tried lot of things but couldnt achieve the same.
shareToSocialNetworking: function () {
cc.director.setNextDeltaTimeZero(true);
var newsize = cc.director.getVisibleSize();
var renderText = new cc.RenderTexture(newsize.width,newsize.height);
renderText.begin();
cc.director.getRunningScene().visit();
renderText.end();
var result = cc.Sprite.create(renderText.getSprite().getTexture());
result.flippedY = true;
this._mainViewNode.addChild(result,6000);
//renderText.saveToFile("screenshot.jpg",cc.IMAGE_FORMAT_PNG);
//var based = renderText.getSprite().getTexture().getStringForFormat().toString();
//var data = based.getData();
var file = new Parse.File("screen.jpg", { base64: this.getBase64(result) });
//var file = new Parse.File("screen.jpg", data, "image/png");
var self = this;
file.save().then(function() {
// The file has been saved to Parse.
alert(file.url);
this.onSharePictureInfoLink(file.url());
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
//
//var ccImage = renderText.newCCImage();
//
//var str = ccImage.getData();
},
is there any workaround that can be done
there is a private variable called _cacheCanvas, which is the instance of the offscreen canvas
you can simply do renderText._cacheCanvas.toDataURL()
Here's how you can take the screnshot from cocos2d-JS
screenshot: function (fileName) {
var tex = new cc.RenderTexture(winSize.width, winSize.height, cc.Texture2D.PIXEL_FORMAT_RGBA8888);
tex.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
tex.begin();
cc.director.getRunningScene().visit();
tex.end();
var imgPath = jsb.fileUtils.getWritablePath();
if (imgPath.length == 0) {
return;
}
var result = tex.saveToFile(fileName, cc.IMAGE_FORMAT_JPEG);
if (result) {
imgPath += fileName;
cc.log("save image:" + imgPath);
return imgPath;
}
return "";
}
then make a Java call from Javascript
public static void ScreenShot()
{
Bitmap imageBitmap = BitmapFactory.decodeFile(Cocos2dxHelper.getCocos2dxWritablePath() + "/" + "screenshot.png");
String fileHolder = "SampleFolder";
File filepathData = new File("/sdcard/" + fileHolder);
//~~~Create Dir
try {
if (!filepathData.exists())
{
filepathData.mkdirs();
filepathData.createNewFile();
FileWriter fw = new FileWriter(filepathData + fileHolder);
BufferedWriter out = new BufferedWriter(fw);
String toSave = String.valueOf(0);
out.write(toSave);
out.close();
}
}
catch (IOException e1) {
}
//~~~Create Image
File file = new File("/sdcard/" + "Your filename");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
imageBitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e) {}
Uri phototUri = Uri.fromFile(file);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
//~~~Add Code Below
}
Do not forget to add permission for external storage

NativeProcess is not Supported AIR 3.2 Desktop?

I am creating an application which capture the screenshot of the desktop.
When I'm compiling and run the application on Flash, only than it will works fine but when I published it with AIR 3.2 Desktop. Than It will not supported the NativeProcess.
I am running the application on Mac Machine.
Here is the below code which I am using:
if (NativeProcess.isSupported)
{
var file:File = File.desktopDirectory;
if (Capabilities.os.toLowerCase().indexOf("win") > -1)
{
file = file.resolvePath("bin/");
}
else if (Capabilities.os.toLowerCase().indexOf("mac") > -1)
{
file = file.resolvePath("/usr/sbin/screencapture/");
trace(" in "+file.nativePath);
status.text = file.nativePath;
}
var str = "screencapture" + String(count) + ".png";
trace(" String "+str);
var args:Vector.<String> = new Vector.<String>();
args[0] = str;
var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
nativeProcessStartupInfo.arguments = args;
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.desktopDirectory;
process = new NativeProcess();
process.start(nativeProcessStartupInfo);
}
else
{
trace("Native Process not supported");
status.text = " Native Process not supported";
}
Any Help is highly appreciated

Decode/Encode .swf file

I have this .swf file: http://www.mediafire.com/download/hrr3c6c188jsgvd/upload.swf
I need to change something in this file, so I have this website http://www.showmycode.com/ decode the file and got those code:
if (!hasOwnProperty("_load05626E90")) {
_load05626E90 = true;
telltarget ("..") {
var copyright = function () {
telltarget ("..") {
geturl("http://www.google.com/search?q=PHP+Script+c-Image+Uploader+3.0", "_blank");
}
};
}
}
else {
// unexpected jump
}
var author = function () {
telltarget ("..") {
geturl("http://chiplove.biz", "_blank");
}
};
// unexpected jump
// unexpected jump
var uploadItem = function (num) {
telltarget ("..") {
var item = flash.net.FileReference(list[num]);
item.addlistener(listener2);
item.upload((((((((((("upload.php?watermark=" + watermark) + "&logo=") + logo) + "&resize=") + resize) + "&server=") + server) + "&q=") + q)+ "&account=") + account)+ "&password=") + password);
}
};
// unexpected jump
// unexpected jump
var FileChooser = function () {
telltarget ("..") {
var fileRef = new flash.net.FileReferenceList();
fileRef.addlistener(listener);
fileRef.browse(allTypes);
}
};
// unexpected jump
// unexpected jump
};
stop();
//---------------------------------------------------------------------- //Frame 1 //----------------------------------------------------------------------
this.menu = new contextmenu();
this.menu.hidebuiltinitems();
this.menu.customitems.push(new contextmenuitem("PHP Script - c-Image Uploader 3.0", copyright));
this.menu.customitems.push(new contextmenuitem("Powered by chiplove.9xpro", author));
//---------------------------------------------------------------------- //Symbol 3 Button //----------------------------------------------------------------------
on (press) {
var listener = new object();
var listener2 = new object();
var itemnum = 0;
var numfiles = 0;
delete _global.__resolve;
_global.__resolve = _global.__debugResolve;
if (list == undefined) {
var list = null;
}
var allTypes = new array();
var imageTypes = new object();
imageTypes.description = "Images (*.jpg; *.jpeg; *.jpe; *.gif; *.png;)";
imageTypes.extension = "*.jpg; *.JPG; *.jpeg; *.jpe; *.gif; *.png;";
allTypes.push(imageTypes);
listener.onselect = function (fileRefList) {
list = fileRefList.fileList; numfiles = list.length;
uploadItem(itemnum);
};
listener2.onOpen = function (file) { };
listener2.onProgress = function (file, bytesloaded, bytestotal) {
flash.external.ExternalInterface.call("loading");
};
listener2.onComplete = function (file) { };
listener2.onUploadCompleteData = function (file, data) {
var loadvars = new loadvars();
loadvars.decode(data);
flash.external.ExternalInterface.call("displaypic", file.name, loadvars.image);
itemnum = itemnum + 1;
if (itemnum < numfiles) {
uploadItem(itemnum);
}
else {
flash.external.ExternalInterface.call("responseStatus", "Done!");
}
};
flash.external.ExternalInterface.addCallBack("FileChooser", this, FileChooser);
flash.external.ExternalInterface.call("clearlist");
FileChooser();
}
I think this is Action Script code, so after make some little change I get flash builder to recompile it, however, flash builder show a lot of red underline (syntax error) in my code and can't build those code to .swf file again. I wonder if the code I got from showmycode.com is correct, or is it action script? If the code I got from showmycode.com is not correct, how can I decode, edit, then encode again that "upload.swf" file?

Problems loading XML file (url cannot load) on local machine

I'm trying to have my flash application interpret an XML file. My code looks like:
function onFinish(success_boolean, results_obj, xml)
{
if (success_boolean)
{
play ();
} // end if
} // End of the function
Stage.align = "MC";
Stage.scaleMode = "noScale";
url = "25358";
_root.cacheKiller = "true";
stop ();
var parsed_obj = {};
var unCash = new Date().getTime();
if (_root.cacheKiller == "true")
{
fileToLoad = url + "_main.xml?cacheKiller=" + unCash;
fileToLoad = url + "_main.xml";
}
else
{
fileToLoad = url + "_main.xml";
} // end else if
gs.dataTransfer.XMLParser.load(fileToLoad, onFinish, parsed_obj);
_root.emp.useHandCursor = 0;
_root.mus = 1;
_root.n = 1;
_root.num = 1;
the output i get is:
Error opening URL 'file:///C|/try/25358undefined'
Does anyone have any idea why i can't access this file? I've verified that the URL works.
You have a wrong url. I mean that fileToLoad contains a wrong value. Try to trace this variable.