stream bytearray to server using flash - actionscript-3

I can easily send bytearray to server using these codes :
var req:URLRequest = new URLRequest(_var1);
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
req.data = DATAS;
var loader:URLLoader = new URLLoader(req);
in this data , DATAS is a bytearray , and it is ready, but I want to send byterray that is generated live and have not length in fact .
I want to stream bytearray , How can I do this ?

You need Socket connection:
var socket:Socket = new Socket();
socket.connect(host, port);
socket.addEventListener(Event.CONNECT, function(event:Event):void
{
socket.writeBytes(DATAS);
});
UPD for the test code for the comments:
var _buffer:ByteArray = new ByteArray();
_buffer.writeByte(0xFF);
trace("_buffer=",ByteArrayUtil.getHexBytesString(_buffer));
var ou:ByteArray = new ByteArray();
ou.writeBytes(_buffer , 0 ,_buffer.length);
_buffer.clear();
trace("ou=\t", ByteArrayUtil.getHexBytesString(ou));
trace("_buffer=", ByteArrayUtil.getHexBytesString(_buffer));
public static function getHexBytesString(array:ByteArray, colons:Boolean=false, position:int = 0, len:int = 0):String {
var s:String = "";
if(!array)
return s;
if(len)
{
len += position;
len = Math.min(len, array.length);
}
else
len = array.length;
for (var i:int=position;i<len;i++) {
s+=("0"+array[i].toString(16)).substr(-2,2).toUpperCase();
if (colons && i<len-1) s+= "-";
}
return s;
}
output:
_buffer= FF
ou= FF
_buffer=

Related

How to resize image before uploading it ?

In my AIR app, the user can take a photo (from CameraRoll or CameraUI) and save it to a server.
Is there a way to automatically resize the image (800x600) in order to have a lighter file ?
Here's my code :
var now:Date = new Date();
var saveDirectory:String= "MyApp/PhotoUploads";
var fileName:String = "MyPhoto" + now.fullYear + now.month + now.day + now.hours + now.minutes + now.seconds + ".jpg";
var photoFile:File=File.documentsDirectory.resolvePath(saveDirectory+"/"+ fileName);
function imageSelected( event:MediaEvent ):void{
var mp:MediaPromise = event.data;
dataSource = mp.open();
readMediaData();
}
function readMediaData():void{
var imageBytes:ByteArray = new ByteArray();
dataSource.readBytes( imageBytes );
var stream:FileStream = new FileStream();
stream.addEventListener( Event.CLOSE,photoFileSaved);
stream.openAsync( photoFile,FileMode.WRITE);
stream.writeBytes( imageBytes );
stream.close();
}
function photoFileSaved(evt:Event):void{
photoUpload();
}
function photoUpload():void{
photoFile.upload( req );
photoFile.addEventListener( ProgressEvent.PROGRESS, progress_func );
photoFile.addEventListener( IOErrorEvent.IO_ERROR, ioErrorMedia );
photoFile.addEventListener( Event.COMPLETE, complete_func );
}
Apparently I can't do :
mp.width = 200;
mp.height= 200;
So how can I do that ?
var scale:Number = .6;
var m:Matrix = new Matrix();
m.scale (scale,scale);
var bmp:BitmapData = new BitmapData(sourceMc.width, sourceMc.height, false);
bmp.draw (sourceMc,m);

How to assign/parse JSON data from 1 as file to another?

and trying to create this search form with a few fields and a search button,when search button is clicked, it goes to next page to display the results and place the results into boxes. E.g. Result 1 has(name,Location,zip), result 2(name,Location,zip) etc
What i need is, php to search and echo the data in JSON, and AS3 VO to receive the data in JSON, Split the data and parse the data to the Vector file and then put them into boxes.
I believe i am just missing 1 final step, i can get the JSON into AS3, i can trace the data. But i can't get it from the first AS(searchVO) file into the Vector AS(SEarchVector) file.
Please give me some opinion thanks.
AS3 VO(receiving the JSON)
function Asandler(event:Event):void{
trace( event.target.data );
var resultString :String = event.target.data;
// parse result string as json object
var resultObject :Object = JSON.parse( resultString );
// loop all keys in the object
for( var s:String in resultObject )
{
switch(s)
{
case 'nobed'
:'nobed', resultObject[s] ;
break;
case 'zip'
:zip=( 'zip', resultObject[s] );
break;
case 'Location'
:Location=( 'Location', resultObject[s] );
break;
case 'price'
:price=( 'price', resultObject[s] );
break;
}}}
SearchVector
public class SearchVectorTest extends MovieClip
{
public function SearchVectorTest()
{
super();
// This part is the parser, i assume i just have to fix this part and the JSON data will come through, but not sure how
var test:Vector.<searchVO1> = new Vector.<searchVO1>();
for (var i:int = 0; i < 10; i++)
{
var tests:searchVO1 = new searchVO1();
tests.nobed = nobed ;
tests.zip = zip;
tests.Location = Location[i];
tests.price = price[i];
test.push(tests);
}
// using that we can loop through every book in the entry
for (var j:int = 0; j < test.length; j++)
{
trace(test[j].nobed);
trace(test[j].zip);
trace(test[j].Location);
trace(test[j].price);
test[j].nobed;
test[j].zip;
test[j].Location;
test[j].price;
}
// loop and put the text into boxes
var currentY:int = 270;
for (var k:int = 0; k < test.length; k++)
{
var Bolder:Listing5 = new Listing5();
Bolder.x=80;
var bf:TextField = new TextField();
var bf1:TextField = new TextField();
var bf2:TextField = new TextField();
var bf3:TextField = new TextField();
bf3.width = 100;
bf.defaultTextFormat = new TextFormat("Arial", 12, 0, null, null, null, null, null, TextFormatAlign.CENTER);
bf.width = 100;
bf.autoSize = TextFieldAutoSize.CENTER;
bf1.width = 100;
bf1.autoSize = TextFieldAutoSize.CENTER;
bf2.autoSize = TextFieldAutoSize.CENTER;
bf3.autoSize = TextFieldAutoSize.CENTER;
bf3.width = 100;
bf1.y= bf.height+5;
// Pulling the textfields content out from the current bookVO
bf.text = test[k].nobed;
bf1.text = test[k].zip;
bf2.text = test[k].Location;
bf3.text = test[k].price;
bf1.x = (Bolder.height-bf.height)*.5
bf3.x = (Bolder.height-bf.height)*.5
bf.x = (Bolder.height-bf.height)*.5
bf.y = (Bolder.height-bf.height)*.15
Bolder.addChild(bf);
Bolder.addChild(bf1);
Bolder.addChild(bf2);
Bolder.addChild(bf3);
// position the object based on the accumulating variable.
Bolder.y = currentY;
//visualAssetForBook.y = (visualAssetForBook.height+15)*k;
addChild(Bolder);
currentY += Bolder.height + 35;
}
}
}
}
Just tried it and it has 2 error,
On this line
searchVOs[i] = new searchVO1(resultArray[i].nobed, resultArray[i].zip, resultArray[i].Location, resultArray[i].price ); in the searchVO file.
Error says Incorrect number of arguments. Expect no more than 0.
And 1 line below that, createBoxes(searchVOs); it has an error,
Call to a possibly undefined method createBoxes.
If you wanted to pass it as VO it's better to use the following solution:
PHP:
$result = mysqli_query($con,$sql);
// create your output array
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) !== false )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
and now you can retrieve your result directly as follow:
SearchVO.as:
package
{
public class SearchVO
{
public var nobed :String;
public var zip :String;
public var location :String;
public var price :Number;
public function SearchVO( nobed:String, zip:String, location:String, price:Number )
{
this.nobed = nobed;
this.zip = zip;
this.location = location;
this.price = price;
}
}
}
ASHandler function:
// retrieve data from php call
var resultString :String = event.target.data;
// parse result string as json object and cast it to array
var resultArray :Array = JSON.parse( resultString ) as Array;
// get the length of the result set
var len:int = resultArray.length;
// create vector of SearchVO
var searchVOs:Vector.<SearchVO> = new Vector.<SearchVO>();
// loop the result array
for( var i:int = 0; i<len; ++i )
{
searchVOs[i] = new SearchVO(resultArray[i].nobed, resultArray[i].zip, resultArray[i].Location, resultArray[i].price );
}
// call a function to create your boxes
createBoxes(searchVOs);
// or maybe create your SearchVector class and pass it your search vector
var mySearchVector:SearchVector = new SearchVector(searchVOs);
createBoxes function:
private function createBoxes( test:vector.<SearchVO> ):void
{
// loop and put the text into boxes
var currentY:int = 270;
for( var k:int = 0; k < test.length; k++ )
{
var Bolder:Listing5 = new Listing5();
Bolder.x=80;
var bf:TextField = new TextField();
var bf1:TextField = new TextField();
var bf2:TextField = new TextField();
var bf3:TextField = new TextField();
bf3.width = 100;
bf.defaultTextFormat = new TextFormat("Arial", 12, 0, null, null, null, null, null, TextFormatAlign.CENTER);
bf.width = 100;
bf.autoSize = TextFieldAutoSize.CENTER;
bf1.width = 100;
bf1.autoSize = TextFieldAutoSize.CENTER;
bf2.autoSize = TextFieldAutoSize.CENTER;
bf3.autoSize = TextFieldAutoSize.CENTER;
bf3.width = 100;
bf1.y= bf.height+5;
// Pulling the textfields content out from the current bookVO
bf.text = test[k].nobed;
bf1.text = test[k].zip;
bf2.text = test[k].Location;
bf3.text = test[k].price;
bf1.x = (Bolder.height-bf.height)*.5
bf3.x = (Bolder.height-bf.height)*.5
bf.x = (Bolder.height-bf.height)*.5
bf.y = (Bolder.height-bf.height)*.15
Bolder.addChild(bf);
Bolder.addChild(bf1);
Bolder.addChild(bf2);
Bolder.addChild(bf3);
// position the object based on the accumulating variable.
Bolder.y = currentY;
//visualAssetForBook.y = (visualAssetForBook.height+15)*k;
addChild(Bolder);
currentY += Bolder.height + 35;
}
}
or SearchVector Class:
public class SearchVectorTest extends MovieClip
{
public function SearchVectorTest(test:Vector.<SearchVO>)
{
super();
// This part is the parser, i assume i just have to fix this part and the JSON data will come through, but not sure how
// REMOVE THAT !
/*
var test:Vector.<searchVO1> = new Vector.<searchVO1>();
for (var i:int = 0; i < 10; i++)
{
var tests:searchVO1 = new searchVO1();
tests.nobed = nobed ;
tests.zip = zip;
tests.Location = Location[i];
tests.price = price[i];
test.push(tests);
}
*/
// using that we can loop through every book in the entry
for (var j:int = 0; j < test.length; j++)
{
trace(test[j].nobed);
trace(test[j].zip);
trace(test[j].Location);
trace(test[j].price);
// trace if you want but calling variable just for fun is not usefull
/*
test[j].nobed;
test[j].zip;
test[j].Location;
test[j].price;
*/
}
// loop and put the text into boxes
var currentY:int = 270;
for (var k:int = 0; k < test.length; k++)
{
var Bolder:Listing5 = new Listing5();
Bolder.x=80;
var bf:TextField = new TextField();
var bf1:TextField = new TextField();
var bf2:TextField = new TextField();
var bf3:TextField = new TextField();
bf3.width = 100;
bf.defaultTextFormat = new TextFormat("Arial", 12, 0, null, null, null, null, null, TextFormatAlign.CENTER);
bf.width = 100;
bf.autoSize = TextFieldAutoSize.CENTER;
bf1.width = 100;
bf1.autoSize = TextFieldAutoSize.CENTER;
bf2.autoSize = TextFieldAutoSize.CENTER;
bf3.autoSize = TextFieldAutoSize.CENTER;
bf3.width = 100;
bf1.y= bf.height+5;
// Pulling the textfields content out from the current bookVO
bf.text = test[k].nobed;
bf1.text = test[k].zip;
bf2.text = test[k].Location;
bf3.text = test[k].price;
bf1.x = (Bolder.height-bf.height)*.5
bf3.x = (Bolder.height-bf.height)*.5
bf.x = (Bolder.height-bf.height)*.5
bf.y = (Bolder.height-bf.height)*.15
Bolder.addChild(bf);
Bolder.addChild(bf1);
Bolder.addChild(bf2);
Bolder.addChild(bf3);
// position the object based on the accumulating variable.
Bolder.y = currentY;
//visualAssetForBook.y = (visualAssetForBook.height+15)*k;
addChild(Bolder);
currentY += Bolder.height + 35;
}
}
}
In all solutions you have to pass the array (or vector) to a function, you cannot retrieve it from nowhere like you do in this part of code:
for (var i:int = 0; i < 10; i++)
{
var tests:searchVO1 = new searchVO1();
tests.nobed = nobed ; // nobed don't exists here
tests.zip = zip; // zip don't exists here
tests.Location = Location[i]; // Location don't exists here and so Location[i]
tests.price = price[i]; // pricedon't exists here and so price[i]
test.push(tests);
}
I hope this could help you
PS: try use capital letters on begin of word only for class names and use lowercase start letters for variables. It's more clear for everyone ;) (ex: MyClassName, myVarName)

AS3 Loading Image URLrequest - getBounds returns no values

I need to get the width and height of a flag I am loading into another movie so I can place it in the right location. Why is my getBounds not picking up the dimensions of the flag?
function displayFlags(evt:Event = null)
{
if(!Lang) { return; }
for (var i:uint = 0; i < Lang.length; i++)
{
//Language = new MovieClip();
//Language.name = Lang[i];
LangButton = new button01();
LangButton.name = Lang[i];
LangButton.btext.text = Lang[i];
LangButton.y = LangButton.height * i;
addChild(LangButton);
var flag:Loader = new Loader();
flag.load(new URLRequest(LangPath[i]+"/flag.png"));
/// Loads Flag into Button
LangButton.addChild(flag);
var fh = flag.getBounds(flag);
trace("FLAG HEIGHT = " + fh.height); // ZERO ZERO ZERO ZERO
// I really need this info to place the flag in the right location.
flag.y = (LangButton.height/2) - (flag.height/2);
}
evt.target.visible = false;
}
UPDATE: MAY 19TH, 2013
I was able to figure out that I need to wait for the flag to be loaded. Now I can get the correct Bounds.. however, now I can not get the movieClip "flag" in the load complete to respond. I don' think it sees the value of flag.
Below is my UPDATED code:
function displayFlags(evt:Event = null)
{
if(!Lang) { return; }
for (var i:uint = 0; i < Lang.length; i++)
{
//Language = new MovieClip();
//Language.name = Lang[i];
LangButton = new button01();
LangButton.name = Lang[i];
LangButton.btext.text = Lang[i];
LangButton.y = LangButton.height * i;
addChild(LangButton);
flag = new Loader();
flag.load(new URLRequest(LangPath[i]+"/flag.png"));
flag.name = Lang[i];
flag.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedFlag(flag));
function loadedFlag()
{
return function()
{
var fh = flag.getBounds(flag);
trace("FLAG HEIGHT = " + fh);
trace("flag Name: "+ flag.name);
flag.alpha = .3;
}
}
LangButton.addChild(flag);
}
evt.target.visible = false;
}
try this :
flag.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
then add function :
function completeHandler(e:Event):void
{
var myFlagInfo:LoaderInfo = e.currentTarget as LoaderInfo;
var myFlag:Loader = myFlagInfo.loader;
var fh = myFlag.getBounds(myFlag);
}

AS3 creating dynamic Loader Names in a loop

EDITED for clarity: I want to load all kinds of images from an external url in a for loop.
I want to call them in a loop and when it's over I start the loop again. however I don't want to call them again with an "http request" rather I would like to loop through the loaded images over and over again.
Is it possible to create a dynamic Loader name in a loop?
Here is the code example:
var Count = 0;
// Loop Begins
var Count:Loader = new Loader();
Count.load(new URLRequest("myurl");
addChild(Count);
Count++;
// End Loop
Another example would be to have a NAME and just add the number on the end. But how
var Count = 0;
// Loop Begins
var MyName+Count:Loader = new Loader();
MyName+Count.load(new URLRequest("myurl");
addChild(MyName+Count);
Count++;
// End Loop
IN SHORT:
I want to load a bunch of images into an Array and loop through the loaded images by calling them later.
Thanks so much!
CASE1 code is how to load images in Sequence.
CASE2 code is how to load images in Synchronized.
First, the URL you want to import all images must be named sequentially.
for example Must be in the following format:
www.myURL.com/img0.jpg
www.myURL.com/img1.jpg
www.myURL.com/img2.jpg
www.myURL.com/img3.jpg
www.myURL.com/img4.jpg
www.myURL.com/img5.jpg
.
.
.
Try the code below, just a test.
CASE1
var imgLoader:Loader;
var imgRequest:URLRequest;
var count:int = -1;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
var isCounting:Boolean;
function loadImage():void
{
count ++;
isCounting = true;
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + count +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
if(count == TOTAL_COUNT)
{
isCounting = false;
count = -1;
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
if( isCounting == false)
{
return;
}
loadImage();
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage();
CASE2
var imgLoader:Loader;
var imgRequest:URLRequest;
const TOTAL_COUNT:int = 10;
var imgBox:Array = [];
function loadImage2():void
{
for(var i:int = 0; i<TOTAL_COUNT; i++)
{
imgLoader = new Loader();
imgRequest = new URLRequest();
imgRequest.url = "www.myURL.com/img" + i +".jpg";
imgLoader.load(imgRequest);
imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
}
}
function onLoadedImg(e:Event):void
{
imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadedImg);
var bmp:Bitmap = e.currentTarget.content;
bmp.x = Math.random() * width;
bmp.y = Math.random() * height;
bmp.width = 100;
bmp.height = 100;
this.addChild(bmp);
imgBox.push(bmp);
}
function unloadedImg(e:IOErrorEvent):void
{
imgLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, unloadedImg);
trace("load Failed:" + e);
}
loadImage2();
If you want access loaded Image. refer a following code. If you do not put them in an array can not be accessed in the future.
for(var int:i=0; i<TOTAL_COUNT; i++)
{
var bitmap:Bitmap = imgBox[i] as Bitmap;
trace("index: " + i + "x: " + bitmap.x + "y: " + bitmap.y, "width: " + bitmap.width + "height: " + bitmap.height);
}
Now that we're on the same page:
var imgArray:Array = new Array;
var totalImages:int = 42;
var totalLoaded:int = 0;
var loaded:Boolean = false;
function loadImages():void{
for(var count:int = 0; count < totalImages; count++){
var image:Loader = new Loader();
image.load(new URLRequest("image" + i + ".jpg");
image.addEventListener(Event.COMPLETE, loaded);
imgArray.push(image);
}
}
function loaded(e:Event):void{
totalLoaded++;
if (totalLoaded == totalImages){
loaded = true;
}
}
function displayImages():void{
if (loaded){
for(var i:int = 0; i < imgArray.length(); i++){
addChild(imgArray[i]);
}
}
}

actionscript: access now object instance

my problem is that after I create the new movie clips I don't know how to access them
var numOfBalls:int = 5;
var balls:Array = new Array();
import flash.utils.getDefinitionByName;
function addBall(instanceName:String) {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return this.newMc;
}
function randRange(start:Number, end:Number) : Number {
return Math.floor(start +(Math.random() * (end - start)));
}
var i = 0;
while ( i < numOfBalls) {
balls[i] = addBall("ball_" + i);
i++;
}
trace (this.balls[0]); // returnes error
trace (this.balls_0); //returnes error
function addBall(instanceName:String):MovieClip {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return newMc;
}
That should fixe it. return typed to MovieClip, and the fix bit,
return newMc instead of this.newMc;
newMC doesn't belong to this.
if you had this.newMc = newMC maybe.
you need to specify what the addBall function is returning
function addBall(instanceName:String):MovieClip {
and you may have to push the balls into the balls array, like
balls[i].push(addBall("ball_" + i));
try this, i'm not sure about your problem
The only thing i can see is the index i where you write the name of the new MovieClip, in ActionScript3 you can't pass a numeric value to a String without convert it with toString() method, try to fix it and see if it works
var numOfBalls:int = 5;
var balls:Array = new Array();
import flash.utils.getDefinitionByName;
function addBall(instanceName:String):MovieClip {
var mcIName:String = "ball";
var tMC:Class = getDefinitionByName(mcIName) as Class;
var newMc:MovieClip = new tMC() as MovieClip;
newMc.name = instanceName;
trace("added " + newMc.name);
newMc.x = randRange(10, 300);
newMc.y = randRange(10, 300);
addChild(newMc);
return this.newMc;
}
function randRange(start:Number, end:Number) : Number {
return Math.floor(start +(Math.random() * (end - start)));
}
var i = 0;
while ( i < numOfBalls) {
// convert i with toString() is requested in as3 or will return ERRORS
balls.push(addBall("ball_" + i.toString ()));
i++;
}
trace (MovieClip(this.balls[0]));