How To Load Image Though URL in action script 3.0 - actionscript-3

I have tested the code in action script 2.0 . it is working great but it does not support GIF so i want it write in action script 3.0.
But i have no idea in this.
var current_loader: Number = 1;
import flash.geom.*;
var current_img: Number = 0;
this.createEmptyMovieClip('img_01', 999);
this.createEmptyMovieClip('img_02', 998);
var loader: MovieClipLoader = new MovieClipLoader();
var listener: Object = new Object();
listener.onLoadComplete = function (target_mc: MovieClip) {
if (target_mc._name == 'img_01') {
img_02._visible = false;
} else {
img_01._visible = false;
}
progress_bar.visible = true;
current_loader.opaqueBackground = 0xFF0000;
};
var interval: Number = setInterval(load_image, 1000);
function load_image() {
loader.addListener(listener);
}
loader.loadClip("http://google/Example3", current_loader);
current_loader = current_loader == 1 ? 2 : 1;
current_img = current_img == images.length - 1 ? 0 : current_img + 1;
}

Very simple in as3:
open Flash IDE, create new .fla file, select first frame, open 'actions (f9)' copy code.
Of course in AS3 it's better to use classes to put your code in.
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
var imageLoader:Loader = new Loader();
var request:URLRequest = new URLRequest("http://dummyimage.com/600x400/e000e0/fff.gif");
imageLoader.load(request);
addChild (imageLoader);
// and all possible listeners
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
imageLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
imageLoader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
function completeHandler(event:Event):void {
trace("completeHandler: " + event);
}
function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
function initHandler(event:Event):void {
trace("initHandler: " + event);
}
function ioErrorHandler(event:IOErrorEvent):void {
trace("ioErrorHandler: " + event);
}
function openHandler(event:Event):void {
trace("openHandler: " + event);
}
function progressHandler(event:ProgressEvent):void {
trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
}
see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Loader.html#includeExamplesSummary

There are simpler ways using straight as3 but this a robust way to load may file types with lots of great documentation. https://greensock.com/LoaderMax-AS3

i did like this .And its Working Perfectly.i think it is the simplest .
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
public class Example extends Sprite {
public function Example() {
var myTimer:Timer = new Timer(1000);// 1 second
myTimer.addEventListener(TimerEvent.TIMER,runMany);
myTimer.start();
function runMany(e:TimerEvent):void {
var loader:Loader=new Loader();
var url:String= "http://Google.Example3.com/latimage.php";
loader.load(new URLRequest(url));
addChild(loader);
}
}
}
}

Related

Newly created objects don't render in Flash

I'm just learning Flash/Actionscript 3 and I'm trying to create a new object using an object already placed in the scene, and this is the code for it:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Scene1 extends MovieClip
{
{
{
{
var theRoot:MovieClip = MovieClip(root);
var mouse:mouse1 = new mouse1();
//Scene1(void);
//onClipEvent(30);
function Scene1():void
{ this.addEventListener(MouseEvent.MOUSE_MOVE, Joe);
}
public function Joe(event:MouseEvent):void
{
mouse.x = mouseX;
mouse.y = mouseY;
mouse.x = 160;
mouse.y = 160;
trace(mouse.x + " " + mouse.y + " " + mouse.z);
}
}
}
}}};
It does trace the position as it should be (160,160), bu object doesn't render, even if I change Z.. although, there aren't any objects that would be blocking it in their view anyway.
This is mouse1:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class mouse1 extends MovieClip
{
{
{
var theRoot:MovieClip = MovieClip(root);
mouse1(void);
//onClipEvent(30);
function mouse1():void
{
//this.z = -20;
trace("WROKZZZ");
}
public function Joe(event:MouseEvent):void
{
//this.x = mouseX;
//this.y = mouseY;
}
}
}
}};
As well as creating the object with new, it needs to be added to the display list (see here: http://www.adobe.com/devnet/flash/quickstart/display_list_programming_as3.html) before it is rendered, so use stage.addChild(mouse) to do this.

Loading issues with AS3

I am trying to load 3 swf files into a parent swf one at a time. However, two of them load the third gives a problem. The other two use my custom preloader but the third one fails to recognize it and shows the default flash loader (with 5 dots). But the loading bar loads up properly. And if I trace this.parent inside my third SWF, it shows up null.
Not sure if I am missing something obvious here but the code for all of them are the same.
package
{
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.MovieClip;
import flash.events.ProgressEvent;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.system.Security;
public class PreloaderMain extends MovieClip
{
private var l:Loader = new Loader();
public function PreloaderMain()
{
LoadGame3(); //THIS DOES NOT LOAD UP
}
private function LoaderIOErrorHandler(i:IOErrorEvent):void
{
trace("IOErrorHandler: " + i.toString());
}
private function loop(e:ProgressEvent):void
{
var perc:Number = e.bytesLoaded / e.bytesTotal;
mLoadingScreen.percent.text = (Math.ceil(perc * 100) + "%").toString();
}
private function done(e:Event):void
{
addChild(l);
}
private function LoadGame1():void // THIS LOADS FINE
{
l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderIOErrorHandler);
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest("SWF1.swf"));
l.x = 20;
l.y = 100;
}
private function LoadGame2():void //THIS LOADS FINE
{
l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderIOErrorHandler);
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest("SWF2.swf"));
l.x = 20;
l.y = 100;
}
private function LoadGame3():void //THIS GIVES A PROBLEM!!
{
l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, LoaderIOErrorHandler);
l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loop);
l.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
l.load(new URLRequest("SWF3.swf"));
l.x = 20;
l.y = 100;
}
}
}

actionscript 3 synchronous loader

I have typical situation where big loop is loading lots of images and its done asynchronous which make browser to frees during loading and I want to make it synchronous but having big trouble doing it. I found this class synchronous loader and it work great but you cant add mouse event listener to loader. Here is sample code:
for (var i = 0; i < items.length; i++) {
item = items[i];
if(item.layer>1){
ld:Loader = new Loader();
ld.load(new URLRequest(item.url));
ld.rotation = item.rotation;
ld.x = item.x ;
ld.y = item.y;
ld.addEventListener(Event.COMPLETE, loadComplete);
ld.scaleX = item.scaleX;
ld.scaleY = item.scaleY;
ld.addEventListener(MouseEvent.MOUSE_DOWN, select);
layers_arr[item.layer].addChild(ld);
}
}
Any idea how this can be done?
like arieljake says, here is a little example on how to use it:
package
{
import com.greensock.TweenLite;
import com.greensock.events.LoaderEvent;
import com.greensock.loading.ImageLoader;
import com.greensock.loading.LoaderMax;
import com.greensock.loading.MP3Loader;
import com.greensock.loading.SWFLoader;
import com.greensock.loading.XMLLoader;
import com.greensock.loading.display.ContentDisplay;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
public class Main extends Sprite
{
public var itemUrl:String;
public var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
public function Main()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
queue.maxConnections = 1; //Checks how much items that can be loaded at the same time
queue.append( new ImageLoader("http://www.myurl.com/myimage.jpg", {name:"photo1", estimatedBytes:2400, container:this, alpha:0,scaleMode:"proportionalInside"}) );
queue.append( new ImageLoader("http://www.myotherurl.com/awesomeimage.jpg", {name:"photo2", estimatedBytes:2400, container:this, alpha:0, scaleMode:"proportionalInside"}) );
queue.addEventListener(LoaderEvent.CHILD_COMPLETE, childCompleteHandler); //checks when a child has completed to load
queue.addEventListener(LoaderEvent.CHILD_PROGRESS, childProgressHandler); //checks the child progress
//prioritize the loader named "photo1"
LoaderMax.prioritize("photo1"); //same as LoaderMax.getLoader("photo1").prioritize();
//start loading
queue.load();
}
protected function childProgressHandler(event:LoaderEvent):void
{
var procent:Number = Math.floor(event.target.progress*100);
var targetName:String = event.target.name;
trace(procent+'% loaded of item: '+targetName);
}
protected function childCompleteHandler(event:LoaderEvent):void
{
var targetName:String = event.target.name;
trace(targetName+' is loaded!');
}
private function completeHandler(event:LoaderEvent):void {
var objects:Array = event.currentTarget.content;
for(var i:uint=0; i < objects.length; i++)
{
var image:ContentDisplay = LoaderMax.getContent(objects[i].name);
TweenLite.to(image, 1, {alpha:1, y:100});
}
trace(event.target + " is complete!");
}
private function errorHandler(event:LoaderEvent):void {
trace("error occured with " + event.target + ": " + event.text);
}
}
}
Check this out: http://www.greensock.com/loadermax/
Let's you specify max number of simultaneous loaders

AIR: how to use FileReference.upload() with POST-based web services (AS3)

I can't seem to get this little AIR app I'm making to work right. There is a single button on the stage, and when the user presses it they are presented with a file browser (FileReference.browse() function). When they select an image file, I want the image to be uploaded to the site imgur.com (http://www.api.imgur.com for those interested).
I'm getting a response from imgur, so I know my app is connecting, but it's returning an error, "No image data was sent to the upload API". Any help is greatly appreciated! (Also I do have an API key, just removed it from this post for obvious reasons :) )
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
public class Document extends MovieClip
{
//file browser var
var myFileReference:FileReference = new FileReference();
//file loader var
private var loader:URLLoader;
//string constants
private const API_KEY:String = "******REMOVED*******";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function Document()
{
// constructor code
browse_btn.addEventListener(MouseEvent.CLICK, browse);
}
function browse(e:MouseEvent)
{
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
myFileReference.browse([imagesFilter]);
myFileReference.addEventListener(Event.SELECT, selectHandler);
myFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
}
function selectHandler(e:Event):void
{
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var params:URLVariables = new URLVariables();
params.date = new Date();
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
//request.contentType = "application/octet-stream";
request.contentType = "multipart/form-data";
request.method = URLRequestMethod.POST;
request.data = params;
myFileReference.upload(request);
try
{
myFileReference.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
function responseHandler(e:DataEvent):void
{
trace("responseHandler() initaialized");
var res:XML = XML(e.data);
trace(res);
}
}
}
there's actually an example for AS3 on their site:
package
{
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
public class ImgurExample
{
private var loader:URLLoader;
private const API_KEY:String = "<api key>";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function ImgurExample() {
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onCookieSent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Create a bitmapdata instance of a movieclip on the stage.
var mc:MovieClip;
var b:BitmapData = new BitmapData(mc.width, mc.height, true);
b.draw(mc);
var png:ByteArray = PNGEncoder.encode(b);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png; // set the data object of the request to your image.
loader.load(request);
}
// privates
private function onSend(e:Event):void {
var res:XML = new XML(unescape(loader.data));
trace(res);
}
private function onIOError(e:IOErrorEvent):void {
trace("ioErrorHandler: " + e);
// Handle error
}
private function onSecurityError(e:SecurityErrorEvent):void {
trace("securityErrorHandler: " + e);
// handle error
}
}
}
http://api.imgur.com/examples

Do you know if there's any problem with netstream.appendBytes() for streaming?

I use netstream.appendBytes to get the streaming (flv) from http, but works intermittently (it works, after refresh, doesn't work, then it works and so on...)
What is the problem?, I have not idea
My code is:
import flash.display.*;
import flash.events.*
import flash.net.*;
import flash.utils.ByteArray;
import com.hurlant.util.Hex;
var videoURL:String = "http://url/vivo/flash";
//elemento de conexíon
var conn:NetConnection = new NetConnection();
conn.connect(null);
//stream de red
var stream:NetStream;
//conexión
stream = new NetStream(conn);
//oyente
stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
function Play()
{
var urlStream:URLStream = new URLStream();
//oyentes de URLStream
urlStream.addEventListener(StatusEvent.STATUS, inStatus);
urlStream.addEventListener(Event.COMPLETE, completeHandler);
urlStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
urlStream.addEventListener(ProgressEvent.PROGRESS, oyenteProcesoCarga);
//urlStream.addEventListener(ProgressEvent.PROGRESS, describeProcesoCarga);
urlStream.addEventListener(IOErrorEvent.IO_ERROR, ioError);
//Video
var video:Video = new Video(640,480);
video.attachNetStream(stream);
addChild(video);
stream.play(null);
urlStream.load(new URLRequest(videoURL));
}
function ioError(event:IOErrorEvent):void
{
textArea.text += event + "\n";
}
function oyenteProcesoCarga(event:ProgressEvent):void
{
var encr:ByteArray = new ByteArray();
event.target.readBytes(encr);
stream.appendBytes(encr);
}
function describeProcesoCarga(event:ProgressEvent):void
{
if (event.target.bytesAvailable > 0){
var encr:ByteArray = new ByteArray();
event.target.readBytes(encr);
}
}
function securityErrorHandler(event:SecurityErrorEvent):void {
}
function asyncErrorHandler(event:AsyncErrorEvent):void {
// ignore AsyncErrorEvent events.
}
function completeHandler(event:Event):void {
}
function inStatus(event:StatusEvent):void {
}
Play();
Maybe use a stream buffer as HTTP is TCP so not all packets arrive at time.