How to resize image before uploading it ? - actionscript-3

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);

Related

three.js json loadingmanager model not displayed

I want to preload all models and textures with a loadingbar in my project. For that i use the LoadingManger from three.js but i have problems with preloading the json Models. They load but i am unable to display them. Here is an example.
You can see in the console that 200 Meshs are created. 100 For the Asteroids and 100 for the Ships.
Withoud the LoadingManger i can display the models (asteroids) so there should be no problem with the model. You can see in the example Asteroids that are loaded without the loading manager.
Here my simplified code for the problem
$(function(){
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var debugScene = true;
var controler, camera, controls, scene, renderer;
var objectControls;
var ship1geometry,ship1material;
////////////////////////////////////////////////////////
//LOADMANGER
////////////////////////////////////////////////////////
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (ship1geometry) {
var ship1material = new THREE.MeshFaceMaterial();
}, "models");
function init() {
var width = window.innerWidth;
var height = window.innerHeight;
camera = new THREE.PerspectiveCamera( 45, width / height, 1, 10000000 );
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 1500;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor("black");
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
var container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
controls.minDistance = 50;
controls.maxDistance = 300000;
controls.autoRotate = false;
controls.autoRotateSpeed = 0.05;
controls.target.x = 0;
controls.target.y = 0;
controls.target.z = 0;
light = new THREE.AmbientLight( 0x666666 );
scene.add( light );
light = new THREE.PointLight( 0xffffff, 1, 10000 );
light.position.set( 0, 0, 0 );
var params = { recursive: true };
objectControls = new ObjectControls( camera, params );
shipCount = 100;
for (var p = 0; p < shipCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var ship = createShipMesh(pX,0,pZ,0,0,0,ship1geometry,ship1material);
scene.add(ship);
}
var loader = new THREE.JSONLoader();
loader.load('models/asteroid.json', function (geometry, mat) {
var material = new THREE.MeshFaceMaterial( mat );
asteroidCount = 100;
for (var p = 0; p < asteroidCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( pX, 0, pZ );
scene.add(mesh);
}
}, "textures");
window.addEventListener( 'resize', onWindowResize, false );
if(debugScene){
var gridHelper = new THREE.GridHelper( 900000, 10000 );
gridHelper.setColors( 0x0000ff, 0x808080 );
scene.add( gridHelper );
var axisHelper = new THREE.AxisHelper( 500 );
scene.add( axisHelper );
console.log(scene);
}
}
function onWindowResize() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
var lastTimeMsec= null;
var nowMsec= null;
function animate() {
requestAnimationFrame( animate );
render();
update();
}
function update(){
controls.update();
objectControls.update();
}
function render() {
renderer.render( scene, camera );
}
function createShipMesh(positionX,positionY,positionZ,centerX,centerY,centerZ,geometry,material){
positionX = centerX + positionX;
positionY = centerY + positionY;
positionZ = centerZ + positionZ;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( positionX, positionY, positionZ );
objectControls.add( mesh );
mesh.select = function(){
controls.target.x = position.x;
controls.target.y = position.y;
controls.target.z = position.z;
controls.dollyIn(2);
controls.minDistance = 20;
}
return mesh;
}
});
Okay i found the problem on my own. the Loading Manager works with json but my mistake was to set the variable ship1geometry global and was thinking that the loader would overwrite this variable so that i can use it later in the scene. That was wrong. I just needed to assign the response from the loader in my globaly set variable. So here is the right code
var ship1geometry,ship1material
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (geometry,mat) {
ship1geometry = geometry;
ship1material = new THREE.MeshLambertMaterial({map:mat });
}, "textures");
function init(){
...
}

stream bytearray to server using flash

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=

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]);
}
}
}

How to get dynamic TextInput field values in Actionscript 3

Hi creating dynamic TextInput fields in a function. Need to get the values of those fields in another function. Can anyone throw some light on this.
for(var i:int=0;i<answers.length;i++)
{
txtbox = new spark.components.TextInput();
var lblBox:spark.components.Label = new spark.components.Label();
lblBox.id = "lbl"+i.toString();
lblBox.text = String(answersLabel.getItemAt(i) );
lblBox.width = 10
lblBox.x = xPos-15;
lblBox.y = yPos;
QuestionAnswer.addElement(lblBox);
txtbox.id = "text"+i.toString();
txtbox.x = xPos;
txtbox.y = yPos;
QuestionAnswer.addElement(txtbox);
xPos += 200;
}
var txt:TextField;
var i:uint;
var ary:Array = new Array();
function txtCreation ():void {
for( i=0;i<5;i++)
{
txt = new TextField();
txt.text = "txt"+i;
addChild(txt);
txt.x = 50 + txt.width *i;
txt.y = 20;
ary.push(txt);
}
}
txtCreation();
for(i=0;i<ary.length;i++)
{
trace("array values : " +ary[i].text);
}
Just look at the text variable for the textfield.
var textFromField : String = myInputText.text;

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]));