ByteArray to Sprite

Hi   I'm having problems with having my bytearray (which is an image) drawn into a sprite. This is my attempt so far:
var imgB:BitmapData = new BitmapData(271, 278, true, 0xff0000);
imgB.setPixels(new Rectangle(0,0,271,278), $imgData);
$image.graphics.beginBitmapFill(imgB,new Matrix(), false, true);
My byteArray is $imgData, and the sprite that I want to draw to is $image. When I run the above code I get EOF error:
Error: Error #2030: End of file was encountered.      at flash.display::BitmapData/setPixels()
Any thoughts?  Thank you

I'm not sure what you're trying to do here...but you cannot use the binary data you loaded with a URLLoader as bitmapData if it was loaded from a png or jpeg for example. Those file formats need to be decoded into bitmapData - using the player's native support for that seems best.
There does seem to be a frame delay with the loadBytes method and you can't catch it using the COMPLETE event, as you say.
I got it working like this (perhaps there is a better way than using the enterFrame, but I just did this quickly to check)
var $image:Sprite=new Sprite();
addChild($image);
var myBitmapData:BitmapData;
var imageLoader:Loader = new Loader()
var dataLoader:URLLoader=new URLLoader();
dataLoader.dataFormat = flash.net.URLLoaderDataFormat.BINARY
dataLoader.addEventListener(Event.COMPLETE,completeHandler)
function loadImage(url:String):void{
    var req:URLRequest=new URLRequest(url);
    dataLoader.load(req)
function completeHandler(e:Event):void{
    //use enterFrame to check for loaded content
    imageLoader.addEventListener(Event.ENTER_FRAME,imageDecodeHandler);
    imageLoader.loadBytes(e.currentTarget.data);
function imageDecodeHandler(e:Event):void{
    if (imageLoader.content) {
        trace('loaded')
        imageLoader.removeEventListener(Event.ENTER_FRAME,imageDecodeHandler);
        myBitmapData = Bitmap(imageLoader.content).bitmapData;
        //imageLoader.content width and height available now as well as myBitmapdata.rect etc
        $image.graphics.beginBitmapFill(myBitmapData,null,true,true);
        $image.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
        $image.graphics.endFill()
    } else {
        trace('not yet loaded')
//substitute a local image file here:
loadImage("46.png")

Similar Messages

  • SampleLinear doesn't work when scaling outCoord using ByteArray or Vector. Number

    Hi,
    I think I've found a bug in Pixel Bender that's so far been missed.
    If you want to upsample a buffer using a ShaderJob and ByteArray/Vector.<Number> it doesn't work with sampleLinear, only sampleNearest.  Using sampleLinear it returns a buffer with mostly black pixels but with every 2nd pixel (for upsampling to a double sized buffer) written to.  So basically it looks like it's upsampling but only writing to some of the target pixels...
    Btw, I'm talking about in Flash here.   And I need to use ByteArray/Vector.<Number> instead of BitmapData as I need to process 32-bit data.
    Strangely it works in the PB toolkit in all of the modes (GPU, CPU, Flash).
    Am I doing something wrong or is this a known issue?
    Here's my sample code:
    package 
              import flash.display.Bitmap;
              import flash.display.BitmapData;
              import flash.display.Shader;
              import flash.display.ShaderJob;
              import flash.display.ShaderPrecision;
              import flash.display.Sprite;
              import flash.display.StageQuality;
              import flash.geom.Vector3D;
              import flash.utils.ByteArray;
              import flash.utils.Endian;
              import flash.utils.Timer;
              public class Test_Upscale extends Sprite
                        [Embed ( source = "../data/embed/pixelbender/bilinearresample.pbj", mimeType = "application/octet-stream" ) ]
                        private var BilinearScalingKernel:Class;
                        public function Test_Upscale()
                                  const srcWidth:int = 256;
                                  const srcHeight:int = 256;
                                  const dstWidth:int = 256;
                                  const dstHeight:int = 256;
                                  this.stage.quality = StageQuality.BEST;
                                  // Create noise input buffer
                                  var input:ByteArray = new ByteArray();
                                  input.endian = Endian.LITTLE_ENDIAN;
                                  input.length = srcWidth * srcHeight * 4 * 4;
                                  for (var i:int = 0; i < srcWidth*srcHeight; i++)
                                            var val:int = Math.random() * 255.0;
                                            input.writeFloat(val);
                                            input.writeFloat(val);
                                            input.writeFloat(val);
                                            input.writeFloat(255.0);
                                  input.position = 0;
                                  // Create output buffer
                                  var output:ByteArray = new ByteArray();
                                  output.endian = Endian.LITTLE_ENDIAN;
                                  output.length = dstWidth * dstHeight * 4 * 4;
                                  // Resample
                                  Resample(input, srcWidth, srcHeight, dstWidth, dstHeight, output);
                                  // Display as a bitmap
                                  this.addChild(new Bitmap(ToBitmap(dstWidth, dstHeight, output) ));
                        private static function ToBitmap(width:int, height:int, data:ByteArray):BitmapData
                                  data.position = 0;
                                  var bmp:BitmapData = new BitmapData(width, height, false);
                                  var idx:int = 0;
                                  for (var j:int = 0; j < height; j++)
                                            for (var i:int = 0; i < width; i++)
                                                      var r:int = data.readFloat() as int;
                                                      var g:int = data.readFloat() as int;
                                                      var b:int = data.readFloat() as int;
                                                      data.readFloat();
                                                      var c:int = r + (g << 8) + (b << 16);
                                                      bmp.setPixel(i, j, c);
                                                      idx++;
                                  return bmp;
                        public function Resample(src:ByteArray, srcWidth:int, srcHeight:int, dstWidth:int, dstHeight:int, dst:ByteArray):void
                                  // create and configure a Shader object
                                  var shader:Shader = new Shader();
                                  shader.precisionHint =ShaderPrecision.FULL;
                                  shader.byteCode = new BilinearScalingKernel();
                                  shader.data.src.input = src;
                                  shader.data.src.width = srcWidth;
                                  shader.data.src.height = srcHeight;
                                  shader.data.scaley.value = [0.5];
                                  var job:ShaderJob = new ShaderJob(shader, dst, dstWidth, dstHeight);
                                  job.start(true); // true flag runs the job synchronously.
    <languageVersion : 1.0;>
    kernel BilinearResample
    <   namespace : "com.test.pixelbender";
        vendor : "me";
        version : 1;
        description : "bilinear";
    >
        input image4 src;
        output pixel4 dst;
        parameter float scaley;
        void
        evaluatePixel()
            dst = sampleLinear(src, outCoord() * float2(scaley, scaley)); // bilinear scaling

    My bad...
    PIxel bender is fine, the bug was in my code that converts the floats back to a BitmapData
    It seems that
        var r:int = data.readFloat() as int;
    does something strange.. If I just remove the "as int" it works fine...  still not sure why though
    -Andrew

  • Convert ios photo(mediapromise) into byteArray ?

    hello
    I'm trying to convert ios photo into bytearray. Because I want send the photo from iphone to AIR in laptop.
    I've found some tutorial looks great and should work:
    http://forums.adobe.com/post!input.jspa?container=4434&containerType=14
    the method is to use "mediaPromise.open()" and get the byte data.
    but I always got an error blow:
    ArgumentError: Error #1063: Argument count mismatch on Main/selectHandler(). Expected 0, got 1.
    dose anyone bump into the same error as me?
    my code is below:
    package
              import flash.display.Sprite;
              import flash.events.Event;
              import flash.events.IEventDispatcher;
              import flash.events.MediaEvent;
              import flash.events.MouseEvent;
              import flash.media.CameraRoll;
              import flash.media.MediaPromise;
              import flash.utils.ByteArray;
              import flash.utils.IDataInput;
              public class Main extends Sprite
                        public var dataSource:IDataInput;
                        public var cameraRoll:CameraRoll=new CameraRoll();
                        public var but_select:Sprite=new Sprite()
                        public function Main()
                                  super();
                                  but_select.graphics.beginFill(0xFF0000)
                                  but_select.graphics.drawCircle(stage.stageWidth / 2, stage.stageHeight / 2, 50)
                                  addChild(but_select)
                                  but_select.addEventListener(MouseEvent.CLICK, selectHandler)
                        public function selectHandler():void
                                  if (CameraRoll.supportsBrowseForImage)
                                            cameraRoll.addEventListener(MediaEvent.SELECT, imageSelected);
                                            cameraRoll.browseForImage();
                                   else
                                    trace("Image browsing is not supported on this device.");
                        private function imageSelected(event:MediaEvent):void
                                trace("Media selected...");
                                  var imagePromise:MediaPromise=event.data;
                                  dataSource=imagePromise.open();
                                  if (imagePromise.isAsync)
                                  trace("Asynchronous media promise.");
                                            var eventSource:IEventDispatcher=dataSource as IEventDispatcher;
                                            eventSource.addEventListener(Event.COMPLETE, onMediaLoaded);
                                   else
                                              trace("Synchronous media promise.");
                                            readMediaData();
                        private function onMediaLoaded(event:Event):void
                                  trace("Media load complete");
                                  readMediaData();
                        private function readMediaData():void
                                  var imageBytes:ByteArray=new ByteArray();
                                  dataSource.readBytes(imageBytes);
                                  trace("imageBytes= " + imageBytes)

    it's wierd but the code below is working:
    package
              import flash.desktop.NativeApplication;
              import flash.display.Loader;
              import flash.display.Sprite;
              import flash.display.StageAlign;
              import flash.display.StageScaleMode;
              import flash.display.graphics;
              import flash.events.ErrorEvent;
              import flash.events.Event;
              import flash.events.IEventDispatcher;
              import flash.events.IOErrorEvent;
              import flash.events.MediaEvent;
              import flash.events.MouseEvent;
              import flash.media.CameraRoll;
              import flash.media.MediaPromise;
              import flash.utils.ByteArray;
              import flash.utils.IDataInput;
              public class Main extends Sprite
                        private var cameraRoll:CameraRoll = new CameraRoll();
                        public var ball:Sprite=new Sprite()
                        private var dataSource:IDataInput;
                        private var eventSource:IEventDispatcher;
                        public function Main()
                                  this.stage.align = StageAlign.TOP_LEFT;
                                  this.stage.scaleMode = StageScaleMode.NO_SCALE;
                                  ball.graphics.beginFill(0xFF0000)
                                  ball.graphics.drawCircle(stage.stageWidth/2,stage.stageHeight/2,50)
                                  addChild(ball)
                                  ball.addEventListener(MouseEvent.CLICK,selectHander)
                        private function selectHander(e:MouseEvent):void
                                  if( CameraRoll.supportsBrowseForImage )
      trace( "Initializing app..." );
                                            cameraRoll.addEventListener( MediaEvent.SELECT, imageSelected );
                                            cameraRoll.addEventListener( Event.CANCEL, browseCanceled );
                                            cameraRoll.addEventListener( ErrorEvent.ERROR, mediaError );
                                            cameraRoll.browseForImage();
      else
      trace( "Image browse is not supported.");
                        private function imageSelected( event:MediaEvent ):void
      trace( "Media selected..." );
                                  var imagePromise:MediaPromise = event.data;
                                  dataSource = imagePromise.open();
                                  if( imagePromise.isAsync )
      trace( "Asynchronous media promise." );
                                            eventSource = dataSource as IEventDispatcher;
                                            trace( eventSource );
                                            eventSource.addEventListener( Event.COMPLETE, onDataComplete );               
      else
      trace( "Synchronous media promise." );
                                            readMediaData();
                        private function onDataComplete( event:Event ):void
      trace("Data load complete");
                                  readMediaData();
                        private function browseCanceled( event:Event ):void
      trace( "Media select canceled." );
                                  NativeApplication.nativeApplication.exit();
                        private function readMediaData():void
      trace("Main.readMediaData()");
                                  var imageBytes:ByteArray = new ByteArray();
                                  dataSource.readBytes( imageBytes );
                                  trace("imageBytes= "+imageBytes)
      //the rest of this is just testing what we actually read
    //                              trace(imageBytes.length);
    //                              imageBytes.position = 0;
    //                              var string:String = imageBytes.readUTFBytes( 300 );
    //                              trace( string );
                        private function mediaError( error:ErrorEvent ):void
                                  trace( "Error:" + error.text );
                                  NativeApplication.nativeApplication.exit();

  • IMAGEIO IS WORKING BUT BYTEARRAY IS NOT WORKING:

    Hi all
    I am getting images from gmail contacts and trying to store it in DB
    using my http code:InputStream is=urlconnection.getInputStream();
    i could able to store the inputstream in file using:
    BufferedImage filebuffer=ImageIO.read(is);
    FileOutputStream fos=new FileOutputStream("picturerecent.jpg");
    ImageIO.write(filebuffer, "jpg", fos);
    but i was trying to store it in DB using the following code but it is not working.i am having a question that
    how it writing to a file without any problem.why not to database:
    try {
           String url = "jdbc:mysql://localhost:3306/";
             String db = "test";
             String driver = "com.mysql.jdbc.Driver";
                    Class.forName(driver);
                    con = DriverManager.getConnection(url+db,"root","");
                    try{
    PreparedStatement psmnt;
         psmnt = con.prepareStatement("insert into gmailphoto(id,Photo) "+ "values(?,?)");
         psmnt.setInt(1, 9);
         psmnt.setObject(2, is, java.sql.Types.BLOB);
         int s = psmnt.executeUpdate();
           Statement st = con.createStatement();
        try{
            ResultSet rs=st.executeQuery("select photo from gmailphoto where id=9");
            if(rs.next())
              {     //byte[] bytearray = new byte[4096];
                  int size=0;
                File sImage;
    //FIRST TRY
                FileWriter wr=new FileWriter(new File("c:\\imageOutput.jpg"));
                IOUtils.copy(rs.getBlob("photo").getBinaryStream(),wr);
                //SECOND TRY
                BufferedImage bf=ImageIO.read(new ByteArrayInputStream(rs.getBytes("photo")));
                FileOutputStream fout=new FileOutputStream(new File("C:\\imageOut"));
                if(bf!=null)ImageIO.write(bf, "jpg", fout);
                if(wr!=null)
                wr.flush();
                wr.close();
              rs.close();
           }}catch(SQLException e){
                System.out.println(e);
           }Thanks a lot for help

    but i was trying to store it in DB using the following codeThere is no code here that writes to a database. There are two lots of code that write to a file.

  • Multiple Animations for a single MovieClip sprite

    Ok, after hours of exhausting searching, and having to learn how to animate a simple sprite for the 100th time, I hope I might found I more specific, and better explained answer to my problem.
    I'm trying to make a flash game, of course, and I want my main Player sprite to be able to play multiple animations based on specific input. So, a running right animation, a running left animation, a jump animation, and an attack animation.
    At the moment, the most I can seem to achieve is to create a single timeline, with a default frame in the exact middle. Then when player holds left, it plays the previous frame, or scrolls backwards through the timeline. When the Right key is held, it plays forward from the default middle.
    It's ugly and extremely limited. I've tried using the gotoAndStop() and gotoAndPlay() methods, but because the statement checking for the key being pressed is constantly being checked, it will stay on the frame chosen for those methods, rather than move forward along the time line.
    I would greatly appreciate a better method for this, or a more specific tutorial to achieve the goal i'm looking for.
    I've seen mention of the attachMovie() method, but I can not find an understandable explanation of how to properly use it in the way I desire.
    essentially, the sprite will have the default standing frame while no keys are pressed. Then, if the right key is down, it plays the running right animation. When the left key is down, it plays the running left animation. When the jump key is pressed, it plays the jump animation. And when the attack key is pressed, it plays the attack animation.
    I hope that's enough information and that it's understandable, if not, let me know what more you need to know and I'll do my best to explain it more.

    You can do this a number of ways but I will try to explain the what I think is the easiest.
    Step 1
    Draw a box on the stage
    Step 2
    convert this into a movieclip (F8), name this myCharacter (or anything you want really), then press ok. Now select this movieClip and in the properties dialogue box, type "box", again, without the quotes. Then press enter.
    Step 3
    Double click this new movieClip (this should take you into this movieClip timeline)
    Step 4
    Now press F6, 3 times. This wil give you 3 additional key frames on this timeline. You should now have 4 key frames.
    |Step 5
    Select key frame 1 on this timeline and press F8. Type into the diag box "standing", without the quotes. Then select the Movie Clip radio button, if it is not already selected.
    Step 6
    Step 12
    Make sure  your library is in view, if not Ctrl+L. You should see the movement clips you created, running_right, running_left, etc. Double Click any one of these and add the animation your want in these movs.
    There we go, simples.....Test you animation and see how you are doing.
    Select key frame 2 on this timeline and press F8. Type into the diag box "running_right", without the quotes. Then select the Movie Clip radio button, if it is not already selected.
    Step 7
    Select key frame 3 on this timeline and press F8. Type into the diag box "running_left", without the quotes. Then select the Movie Clip radio button, if it is not already selected.
    Step 8
    Select key frame 4 on this timeline and press F8. Type into the diag box "jumping", without the quotes. Then select the Movie Clip radio button, if it is not already selected.
    Great, once you have done this, these new movieClips should now have appeared in your library (press Ctrl+L if you cannot see your library)
    Ok then you have just created your movement MovieClip. You now need to get back to the main timeline. You can just keep on clicking the stage to get back to this location. Once there you need to select the box you have just created and name this "box" for the time being.
    Ok then a little bit of programming now.
    Step 9Create a new layer in the timeline and name it scripts.
    Step 10Then select this layer and press F9 on your keyboard. THis should bring up the scripting pane for this frame.
    Step 11Type in the following code
    box.stop();// when you run this animation, this command will stop your box from doing anything
    var keyBoardListener:Object = new Object();// Creates a new Object for the keyboard presses
    keyBoardListener.onKeyDown = function() {
    if (Key.isDown(Key.LEFT)) {// runnning LEFT action
      _root.box.gotoAndStop(3);// Frame where the running right animation is
    } else if (Key.isDown(Key.RIGHT)) {// running RIGHT action
      _root.box.gotoAndStop(2);// Frame where the running right animation is
    } else if (Key.isDown(Key.UP)) {// JUMPING action
      _root.box.gotoAndStop(4);// Frame where the JUMPING animation is
    keyBoardListener.onKeyUp = function() {
    _root.box.gotoAndStop(1);// When the keys are released, this action takes your animation back to frame 1, where your character is just standing still.
    Key.addListener(keyBoardListener);// this assigns the listener to your key press detection Object.
    Step 12
    Edit the action movs within your library by double clicking each one and adding movement to each. Then test your animation.

  • Follow sprite when the mouse is down, but randomly move when mouse is up?

    I have a sprite that has a Random Movement behavior.
    While the mouse is down, I want it to stop this behavior and initialize a Follow Sprite behavior instead.
    When the mouse is lifted, I want to stop the Follow Sprite behavior and reset/restart the Random Movement behavior.
    Openspark helped me out with a different version of a very similar behavior a long while back, which worked. It switched between Random Movement and Draggable. I tried to edit the code so that it would apply to Follow Sprite instead of Draggable, but it isn't working the way I thought it would.
    The order of behaviors on my sprite is as such:
    followSprite (Follow Sprite)
    moveToward (The behavior described above)
    randomMove (Random Movement)
    turnTowardsMouse (sprite faces mouse when it is clicked)
    Face Destination (if not facing mouse, sprite faces toward the randomized endpoints generated by randomMove)
    This is the moveToward behavior - the middleman that's supposed to be swapping between the two:
    property pSprite
    property pTouching
    on beginSprite(me)
      pSprite = sprite(me.spriteNum)
    end beginSprite
    on mouseDown(me)
      -- Overrule the Random Movement and Rotation behavior until the mouse
      -- is released. See the on prepareFrame() handler for the effect.
      pTouching = TRUE
    end mouseDown
    on prepareFrame(me)
      if pTouching then
        -- Block the event from reaching the Random Movement and Rotation
        -- behavior, so that only the Draggable behavior will work.
        if the mouseDown then
          stopEvent
        else
          -- The user has released the mouse.
          -- Start a new movement in the Random Movement and Rotation behavior.
          pSprite.pPath = VOID
          sendSprite(pSprite, #mNewPath)
          pSprite.pRotate = VOID
          sendSprite(pSprite, #mNewRotation)
          pTouching = 0
        end if
      end if
    end prepareFrame
    Can anyone help me figure this out?
    If you want to imagine a visual, it's essentially a touchscreen fish tank. Fish swim around randomly, but when someone is touching the screen, they approach the point of contact (which is defined by a tiny invisible sprite centered on the cursor).
    Once again, thank you so much to anyone who can help me out. This is part of a capstone undergraduate art project I am doing - and I am far more experienced in making the visuals than I am in coding. I am having to mostly tackle Lingo on my own. Any coding help I've received will be recognized (with permission) on my artist website as well as a thesis paper I am writing that will be published in May.

    As first steps at troubleshooting you could try an SMC reset and a PRAM reset:
    SMC Reset
    Shut down the computer.
    Unplug the computer’s power cord and disconnect peripherals.
    Press and hold the power button for 5 seconds.
    Release the power button.
    Attach the computers power cable.
    Press the power button to turn on the computer.
    Reset PRAM
    Shut down the computer.
    Locate the following keys on the keyboard: Command, Option, P and R.
    You will need to hold these keys down simultaneously in step 4.
    Turn on the computer.
    Press and hold the Command-Option-P-R keys. You must press this key combination before the gray screen appears.
    Hold the keys down until the computer restarts and you hear the startup sound for the second time.
    Release the keys.
    If that doesn't help, what OS are you running? Depending on the OS (Lion/Snow Leopard) will help determine the next step.

  • Problem in Loading Multiple image in Single Sprite/MovieClip

    Hi All,
    I am having a killing problem in loading multiple images in single movie clip/sprite using a separate class.
    Here is the ImageLoader.as class
    package com.project.utils{
        import com.project.*;
        import com.project.utils.*;
        import flash.events.EventDispatcher;
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.events.ProgressEvent;
        import flash.display.Loader;
        import flash.events.IOErrorEvent;
        import flash.net.URLLoader;
        import flash.events.MouseEvent;
        import flash.net.URLRequest;
        import flash.display.Bitmap;
        public class ImageLoader extends EventDispatcher {
            public var imgloader:Loader;
            public var imgMc:MovieClip;
            public var imgObject:Object;
            public var loaded:Number;
            public function ImageLoader():void {
                imgMc = new MovieClip();
                imgObject = new Object();
                imgloader = new Loader();
            public function loadImage(imgHolder:MovieClip, imgObj:Object):void {
                imgMc = new MovieClip();
                imgObject = new Object();
                imgloader = new Loader();
                imgMc = imgHolder;
                imgObject = imgObj;
                imgloader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImgLoad);
                imgloader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onImgLoadProgress);
                imgloader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onImageLoadFailed);
                imgloader.load(new URLRequest(imgObj.FilePath));
            private function onImgLoad(Evt:Event):void {
                var image:Bitmap = Bitmap(Evt.target.content);
                try {
                    imgMc.removeChildAt(0);
                } catch (error:Error) {
                imgMc.addChild(image);
                try {
                    if (imgObject.URL != undefined) {
                        imgMc.buttonMode = true;
                        imgMc.removeEventListener(MouseEvent.CLICK, onImageClicked);
                        imgMc.addEventListener(MouseEvent.CLICK, onImageClicked);
                } catch (err:Error) {
                dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD"));
            private function onImageClicked(evt:MouseEvent):void {
                trace("Image Attrs:"+imgObject.URL +" Target "+imgObject.Target);
            private function onImgLoadProgress(Evt:ProgressEvent):void {
                if (Evt.bytesLoaded>0) {
                    loaded = Math.floor((Evt.bytesLoaded*100)/Evt.bytesTotal);
                    dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD_PROC",loaded));
            private function onImageLoadFailed(Evt:IOErrorEvent):void {
                trace("Image Loading Failed");
                dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD_FAIL"));
    Here I am loading some images using the above class in a for loop, like
                for (var i=0; i < 3; i++) {
                    //imgLoader=new ImageLoader;
                    imgLoader.addEventListener("CustomEvent.ON_IMGE_LOAD",onImageLoad);
                    var target:MovieClip=videolist_mc["list" + mcCount + "_mc"];
                    target.list_mc.visible=false;
                    var imgObj:Object=new Object;
                    imgObj.FilePath=list[i].Thumbnail;
                    imgObj.Url=list[i].Url;
                    imgObj.Target=list[i].Target;
                    target.list_mc.urlObj=new Object  ;
                    target.list_mc.urlObj=imgObj;
                    imgLoader.loadImage(target.list_mc.imgholder_mc,imgObj);
                    target.list_mc.lable_txt.htmlText="<b>" + list[i].Label + "</b>";
                    target.list_mc.imgholder_mc.buttonMode=true;
                    target.list_mc.imgholder_mc.addEventListener(MouseEvent.CLICK,onItemPressed);
                    mcCount++;
    In this case, the ImageLoader.as works only on the last movie clip from the for loop. For example, if i am trying to load three image in three movie clips namely img_mc1,img_mc2 and img_mc3 using the for loop and ImageLoader.as, I am getting the image loaded in the third movie clip only img_mc.
    See at the same time, If i uncomment onething in the for loop that is
    //imgLoader=new ImageLoader;         
    its working like a charm. But I know creating class objects in a for loop is not a good idea and also its causes some other problems in my application.
    So, help to get rid out of this problem.
    Thanks
    -Varun

    package com.project.utils{
        import com.project.*;
        import com.project.utils.*;
        import flash.events.EventDispatcher;
        import flash.display.MovieClip;
        import flash.events.Event;
        import flash.events.ProgressEvent;
        import flash.display.Loader;
        import flash.events.IOErrorEvent;
        import flash.net.URLLoader;
        import flash.events.MouseEvent;
        import flash.net.URLRequest;
        import flash.display.Bitmap;
        public class ImageLoader extends EventDispatcher {
            public var imgloader:Loader;
            public var imgMc:MovieClip;
            public var imgObject:Object;
            public var loaded:Number;
            public function ImageLoader():void {
    // better add you movieclip to the stage if you want to view anything added to it.
                imgMc = new MovieClip();
                imgObject = new Object();
                imgloader = new Loader();
            public function loadImage(filepath:String):void {
                imgloader.contentLoaderInfo.addEventListener(Event.COMPLETE,onImgLoad);
                imgloader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onImgLoadPr ogress);
                imgloader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onImageLoadF ailed);
                imgloader.load(new URLRequest(filepath));
            private function onImgLoad(Evt:Event):void {
                var image:Bitmap = Bitmap(Evt.target.content);
                try {
                    imgMc.removeChildAt(0);
                } catch (error:Error) {
                imgMc.addChild(image);
                try {
                    if (imgObject.URL != undefined) {
                        imgMc.buttonMode = true;
                        imgMc.removeEventListener(MouseEvent.CLICK, onImageClicked);
                        imgMc.addEventListener(MouseEvent.CLICK, onImageClicked);
                } catch (err:Error) {
                dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD"));
            private function onImageClicked(evt:MouseEvent):void {
                trace("Image Attrs:"+imgObject.URL +" Target "+imgObject.Target);
            private function onImgLoadProgress(Evt:ProgressEvent):void {
                if (Evt.bytesLoaded>0) {
                    loaded = Math.floor((Evt.bytesLoaded*100)/Evt.bytesTotal);
                    dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD_PROC",loaded));
            private function onImageLoadFailed(Evt:IOErrorEvent):void {
                trace("Image Loading Failed");
                dispatchEvent(new CustomEvent("CustomEvent.ON_IMGE_LOAD_FAIL"));
    Here I am loading some images using the above class in a for loop, like
                for (var i=0; i < 3; i++) {
                    var imgLoader:ImageLoader=new ImageLoader();
                    imgLoader.addEventListener("CustomEvent.ON_IMGE_LOAD",onImageLoad);
                    var target:MovieClip=videolist_mc["list" + mcCount + "_mc"];
                    target.list_mc.visible=false;
                    var imgObj:Object=new Object;
                    imgObj.FilePath=list[i].Thumbnail;
                    imgObj.Url=list[i].Url;
                    imgObj.Target=list[i].Target;
                    target.list_mc.urlObj=new Object  ;
                    target.list_mc.urlObj=imgObj;
                    imgLoader.loadImage(pass the image file's path/name);
                    target.list_mc.lable_txt.htmlText="<b>" + list[i].Label + "</b>";
                    target.list_mc.imgholder_mc.buttonMode=true;
                    target.list_mc.imgholder_mc.addEventListener(MouseEvent.CLICK,onItemPressed);
                    mcCount++;

  • How to open a PDF File from a ByteArray

    Hi, Fellows,
    I'm having the following problem:
    I have put a PDF file inside a BLOB field in a table in my SQLite database.
    And I can retrieve it from this database without any problem, receiving a ByteArray data type as result.
    What I want to know is what I should do to render this file in my HTML flex object without saving it to a file…
    I used the mx.controls.HTML.data property, but what I see is the TEXT of my PDF file. The mx.controls.HTML.location needs a STRING with the link to a URL site or file.
    Thanks in advance for your help.
    Here, my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx=" http://www.adobe.com/2006/mxml" layout="absolute" width="810" height="620"
          creationComplete="creationCompleteHandler();">
          <mx:Script>
                <![CDATA[
                      import flash.data.*;
                      import flash.filesystem.*;
                       private var _connection:SQLConnection;
                      private var _statement:SQLStatement; 
                 private function creationCompleteHandler():void {
                    var file:File = File.applicationStorageDirectory.resolvePath("arq.db");
                    _connection = new SQLConnection();
                    _connection.addEventListener(SQLEvent.OPEN, openHandler);
                    _connection.openAsync(file, SQLMode.CREATE);
                 private function openHandler(event:SQLEvent):void {
                    var sql:SQLStatement = new SQLStatement();
                    sql.sqlConnection = _connection;
                    sql.text = "CREATE TABLE IF NOT EXISTS arq(" +
                               "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                               "nome TEXT, " + 
                                "arquivo BLOB)";
                    sql.execute();        
                 private function insertFile(identificacao:String, caminho:String):void {
                            var sql:SQLStatement = new SQLStatement();
                            sql.sqlConnection = _connection;
                            var arquivo:File = new File(caminho);
                            var arqStream:FileStream = new FileStream();
                            arqStream.open(arquivo,SQLMode.READ);
                            var arqBlob:ByteArray = new ByteArray();
                            arqStream.readBytes(arqBlob);
                            arqStream.close();
                    sql.text = "INSERT INTO arq(nome, arquivo)" + 
                                "VALUES(@nome, @arquivo)";
                    sql.parameters["@nome"] = identificacao;
                    sql.parameters["@arquivo"] = arqBlob;
                    sql.execute();
                     trace("Arquivo inserido com Sucesso!!!");
                     lb1.text = "Arquivo inserido com Sucesso!!!";
                 private function selectFile(identificacao:String):void {
                             var sql:SQLStatement = new SQLStatement();
                            sql.sqlConnection = _connection;
                    sql.text = "SELECT id, arquivo FROM arq WHERE nome=@nome";
                    sql.parameters["@nome"] = identificacao;
                    trace(sql.text);
                    sql.addEventListener(SQLEvent.RESULT, apresentarDados);
                    sql.execute();
                 private function apresentarDados(event:SQLEvent):void {
                             var statement:SQLStatement = event.target as SQLStatement;
                            var result:SQLResult = statement.getResult();
                            if(result != null && result.data != null) {
                                  var dataset:Array = result.data;
                                  trace(dataset.length);
                            var arqBlob:ByteArray = dataset[0].arquivo;
                       var xx:HTMLLoader = new  HTMLLoader();
                      var ur:URLRequest = new URLRequest();
                      var ul:URLLoader = new URLLoader();
                       //Right now, it's doing nothing
    ur.contentType = "application/pdf";
                       ul.dataFormat = URLLoaderDataFormat.BINARY;
                      ul.data = arqBlob;
                       //Here is my problem - WHAT SHOULD I DO?
    pdfFile.data = arqBlob;
                           trace("Cheguei!!!");
                          lb1.text = "Cheguei!!!";
                             } else {
                                  trace("Não funcionou!!!")
                 private function sair():void {
                      this.exit();
                 ]]>
          </mx:Script>
          <mx:TextInput x="99" y="10" id="arq"/>
          <mx:Label x="10" y="12" text="Identificação:" width="81"/>
          <mx:Button x="168" y="40" label="Apresentar" click="selectFile(arq.text)"/>
          <mx:Button x="728" y="10" label="Sair" width="60" click="sair()"/>
          <mx:TextInput x="417" y="10" id="id1"/>
          <mx:TextInput x="417" y="40" id="cm1"/>
          <mx:Button x="585" y="12" label="Gravar" click="insertFile(id1.text, cm1.text)"/>
          <mx:Label x="291" y="12" text="Identificação:" width="105"/>
          <mx:Label x="291" y="42" text="Caminho Completo:" width="118"/>
          <mx:Label x="615" y="42" width="173" id="lb1"/>
          <mx:HTML id="pdfFile" width="800" height="520" y="79"/>
    </mx:WindowedApplication>

    Bob, Here's some ActionScript code for saving the byte array data to temporary file. (In this code, pdfData is a ByteArray object containing the PDF data.)
    var tempFile:File = File.createTempFile();
    var stream:FileStream = new FileStream();
    stream.open(tempFile, FileMode.WRITE);
    stream.writeBytes(pdfData);
    stream.close();
    Next you can load the file into your Flex HTML control (represented as html in the following code):
    html.location = tempFile.url;
    Here's more information on reading and writing files:
    http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc2. html (for Flex developers)
    http://help.adobe.com/en_US/AIR/1.5/devappsflash/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc2 .html (for Flash developers)
    http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7dc2. html (for Ajax developers)

  • How can I control the playback of a Flash sprite in Director?

    I'm trying the sprite(#).movierate method to specify playing,
    pausing, and rewinding but it's not working. What's the proper way
    of doing it? Any help will be very appreciated!

    sprite(X).play()
    sprite(X).stop()
    sprite(X).rewind()
    The movieRate property belongs to digital video member types.
    Rob
    Rob Dillon
    Adobe Community Expert
    http://www.ddg-designs.com
    412-243-9119
    http://www.macromedia.com/software/trial/

  • How can I check the locV of a sprite on every frame?

    I'd like to know how can I tell Director, in Lingo, to check
    the position of a sprite in every frame in order to use that
    position to set the value of a global variable. I want to avoid
    having an on enterFrame script on every frame as I will need to do
    this with various sprites all the time. I tried an on enterFrame
    movie script but when I check the value of the variable with the
    message window it's always 1 (I initialized the variable with that
    value), regardless of wether the condition is being met on that
    specific frame or not. I also placed an on enterFrame script on the
    sprite and it would not work either. According to the
    documentation, on beginSprite only works if the sprite was not on
    the stage previous, and this sprite will always be on the stage,
    just in a different locV when I need it to be.
    Any suggestions please?

    Here's how you could create a single list containing all the
    locV values that you want:
    global gLocVList
    on enterFrame
    if ilk(gLocVList) <> #propList then
    gLocVList = [:]
    end if
    vSpriteList = [2, 3, 5, 7, 11, 13, 17, 19] -- or other
    spriteNums
    repeat with vSpriteNum in vSpriteList
    vLocV = sprite(vSpriteNum).locV
    gLocVList.setaProp(vSpriteNum, vLocV)
    end repeat
    end enterFrame
    However, it seems rather pointless to do this, as it checks
    the locV of every sprite on every frame whether you need that
    information or not. Since the sprite references are globally
    available anyway, you would use fewer CPU cycles if you just asked
    for...
    sprite(x).locV
    ... (where x is a sprite name or spriteNum, or a variable
    holding such information ) whenever you actually require the value
    of the locV.

  • How can I display a UIComponent in a Sprite container?

    Hi everyone,
    I am stuck in a strange problem, can anyone suggest what I am
    doing wrong here: the TextArea component didn't show in the
    display:
    var text:TextArea = new TextArea();
    text.height = 500;
    text.width = 200;
    text.text = " ... anything in TextArea... ";
    text.x = 10;
    text.y = 10;
    var field:TextField = new TextField();
    field.height = 20;
    field.width = 200;
    field.text = " ... anything in TextField... ";
    field.x = 5;
    field.y = 5;
    var sprite:Sprite = new Sprite();
    sprite.addChild(text);
    sprite.addChild(field);
    this.addChild(sprite);
    Where "this" is a class that extends from Sprite. The
    TextField was displayed, but the TextArea didn't. I have the same
    problem with other components that extends from UIComponent.
    Thanks in advance,
    Carlos

    I imported the class from the package "mx.controls" because I
    don't have the package "fl.controls". So, this is not the problem
    ... I suppose ...

  • How can I animate my sprite to run on scroll and stop when scrolling stops?

    I appreciate everyones help so far.
    I want my illustration of a man to "walk" through my composition as the user scrolls through it.
    I have a sprite created and have made it loop. What sort of code do I need to write to get it to move only on scroll and stop off scroll?
    Thank you guys so much!
    Johnathan

    Hi,
    Thank you for your post.
    Please check the following tutorials for scrolling effects in edge animate.
    http://www.heathrowe.com/adobe-edge-animate-simple-scrollbar-symbols/
    http://www.adobe.com/inspire/2014/01/parallax-edge-animate.html
    Regards,
    Devendra

  • How to load a ByteArray FLV in OSMF?

    I'm working on a local application ( it's not a website or nothing related ) and I have various FLVs with a very simple encryptation method (just like adding 10 at each byte).
    I can load/play them using NetStream.appendBytes() after my decrypt, but that happens only after I read all video data.
    What I really need is to stream those videos from a remote url, and decrypting while receiving data, using a OSMF player that I already have.
    This is my current code just to play my decoded FLV byte array
    private function playBytes(bytes:ByteArray):void
                // detecting it's header
                if (bytes.readUTFBytes(3) != "FLV")
                    _text.appendText("\nFile \""+ file +"\" is not a FLV")
                    return void;
                bytes.position = 0;
                netConnection.connect(null);
                netStream = new NetStream(netConnection);
                netStream.client = { onMetaData:function(obj:Object):void { } }
                video.attachNetStream(netStream);
                addChild(video);
                // put the NetStream class into Data Generation mode
                netStream.play(null);
                // before appending new bytes, reset the position to the beginning
                netStream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN);
                // append the FLV video bytes
                netStream.appendBytes(bytes);
    [I moved the discussion from OSMF, to here, due the lack of attention there]

    I looked at it a couple of month ago and, frankly, don't remember exact package that takes care of it. I don't have OSMF code on this machine - so I cannot look into it now.
    I doubt there are many resources on the web regarding this. This is a very specialized functionality and very few people attempted to do what OSMF does. We have figured out certain aspects but were not able to completely replicate it. Again, it is a very daunting task to search of byte offsets and match with file format specs.

  • Loading sprites from files

    I'm sure this must crop up but I've been unable to find
    anything by searching...
    I am developing a catalogue browser - users scroll through
    thumbnails and click on them to view the product in a larger
    window. However, the catalogue changes frequently and ideally I'd
    like to load the items (sprites) at run time from a specified
    directory so that each 'release' of the catalogue only needs to
    have this directory replaced for it to be up to date.
    I'm thinking to use text files within the root of this
    product directory and subs to identify folder names and product
    names but I've been unable to find any advice on how to load
    sprites via lingo from a filepath.
    Can anyone help?
    Jon

    Hi Jon,
    Actually, you want to load in new members, not sprites. If
    this is an
    app that's on a CD or a hard drive then you can use
    downloadNetThing()
    to download the file to the user's hard drive. You can then
    import,
    open, or link that file to your movie. If this is a graphic,
    you can
    update a cast member using member.fileName(), if this is a
    text file
    then you can open the file and copy the contents into an
    existing, or
    new member.
    There are a number of data base Xtras that can pull in new
    content
    directly from a data base.
    Another option is keep, at least one, cast external and not
    protected.
    You can then update the cast and make it available for
    download. You can
    have this update done at runtime, or you could write another
    app to do
    the update.
    Rob
    Rob Dillon
    Adobe Community Expert
    http://www.ddg-designs.com
    412-243-9119
    http://www.macromedia.com/software/trial/

  • What is the best way of dealing with an "implicit coercion" of an array to a sprite?

    Hello everyone!
         With continued help from this forum I am getting closer to having a working program. I look forward to being able to help others like myself once I finish learning the AS3 ropes.
         I will briefly explain what I am trying to achieve and then follow it up with my question.
    Background
         I have created a 12 x 9 random number grid that populates each cell with a corresponding image based on each cell's numeric value. I have also created a shuffle button that randomizes the numbers in the grid. The problem I am running into is getting my button-click event to clear the current images off the grid in order to assign new ones (i.e. deleting the display stack objects in order to place news ones in the same locations).
    Question
         My question is this: what is the best way to handle an implicit coercion from an array to a sprite? I have pasted my entire code below so that you can see how the functions are supposed to work together. My trouble apparently lies with not being able to use an array value with a sprite (the sprite represents the actual arrangement of the grid on the display stack while the array starts out as a number than gets assigned an image which should be passed to the sprite).
    ============================================================================
    package 
    import flash.display.MovieClip;
    import flash.display.DisplayObject;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.utils.getDefinitionByName;
    public class Blanko extends MovieClip
          // Holds 12*9 grid of cells.
          var grid:Sprite;
          // Holds the shuffle button.
          var shuffleButton:Sprite;
          // Equals 12 columns, 9 rows.
          var cols:int = 12;
          var rows:int = 9;
          // Equals number of cells in grid (108).
          var cells:int = cols * rows;
          // Sets cell width and height to 40 pixels.
          var cellW:int = 40;
          var cellH:int = 40;
          // Holds 108 cell images.
          var imageArray:Array = [];
          // Holds 108 numerical values for the cells in the grid.
          var cellNumbers:Array = [];
          // Constructor calls "generateGrid" and "makeShuffleButton" functions.
          public function Blanko()
               generateGrid();
               makeShuffleButton();
      // Creates and displays the 12*9 grid.
      private function generateGrid():void
           grid = new Sprite;
           var i:int = 0;
           for (i = 0; i < cells; i++)
                cellNumbers.push(i % 9 + 1);
           trace("Before shuffle: ", cellNumbers);
           shuffleCells(cellNumbers);
           trace("After shuffle: ", cellNumbers);
           var _cell:Sprite;
           for (i = 0; i < cells; i++)
                // This next line is where the implicit coercion occurs. "_cell" is a sprite that tries
                   to temporarily equal an array value.
                _cell = drawCells(cellNumbers[i]);
                _cell.x = (i % cols) * cellW;
                _cell.y = (i / cols) * cellH;
                grid.addChild(_cell);
      // Creates a "shuffle" button and adds an on-click mouse event.
      private function makeShuffleButton():void
           var _label:TextField = new TextField();
           _label.autoSize = "center";
           TextField(_label).multiline = TextField(_label).wordWrap = false;
           TextField(_label).defaultTextFormat = new TextFormat("Arial", 11, 0xFFFFFF, "bold");
           _label.text = "SHUFFLE";
           _label.x = 4;
           _label.y = 2;
           shuffleButton = new Sprite();
           shuffleButton.graphics.beginFill(0x484848);
           shuffleButton.graphics.drawRoundRect(0, 0, _label.width + _label.x * 2, _label.height +
                                                _label.y * 2, 10);
           shuffleButton.addChild(_label);
           shuffleButton.buttonMode = shuffleButton.useHandCursor = true;
           shuffleButton.mouseChildren = false;
           shuffleButton.x = grid.x + 30 + grid.width - shuffleButton.width;
           shuffleButton.y = grid.y + grid.height + 10;
           this.addChild(shuffleButton);
           shuffleButton.addEventListener(MouseEvent.CLICK, onShuffleButtonClick);
      // Clears cell images, shuffles their numbers and then assigns them new images.
      private function onShuffleButtonClick():void
       eraseCells();
       shuffleCells(cellNumbers);
       trace("After shuffle: ", cellNumbers);
       for (var i:int = 0; i < cells; i++)
        drawCells(cellNumbers[i]);
      // Removes any existing cell images from the display stack.
      private function eraseCells(): void
       while (imageArray.numChildren > 0)
        imageArray.removeChildAt(0);
      // Shuffles cell numbers (randomizes array).
      private function shuffleCells(_array:Array):void
       var _number:int = 0;
       var _a:int = 0;
       var _b:int = 0;
       var _rand:int = 0;
       for (var i:int = _array.length - 1; i > 0; i--)
        _rand = Math.random() * (i - 1);
        _a = _array[i];
        _b = _array[_rand];
        _array[i] = _b;
        _array[_rand] = _a;
      // Retrieves and assigns a custom image to a cell based on its numerical value.
      private function drawCells(_numeral:int):Array
       var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
       _classRef.x = 30;
       imageArray.push(_classRef);
       imageArray.addChild(_classRef);
       return imageArray;
    ===========================================================================
         Any help with this is greatly appreciated. Thanks!

    Rothrock,
         Thank you for the reply. Let me address a few things here in the hopes of allowing you (and others) to better understand my reasoning for doing things in this manner (admittedly, there is probably a much better/easier approach to what I am trying to accomplish which is one of the things I hope to learn/discover from these posts).
         The elements inside my "imageArray" are all individual graphics that I had imported, changed their type to movie clips using .Sprite as their base class (instead of .MovieClip) and then saved as classes. The reason I did this was because the classes could then be referenced via "getDefinitionByName" by each cell value that was being passed to it. In this grid every number from 1 to 9 appears randomly 12 times each (making the 108 cells which populate the grid). I did not, at the time (nor do I now), know of a better method to implement for making sure that each image appears in the cell that has the corresponding value (i.e. every time a cell has the value of 8 then the custom graphic/class "skin8" will be assigned to it so that the viewer will be able to see a more aesthetically pleasing numerical representation, that is to say a slightly more fancy looking number with a picture behind it). I was advised to store these images in an array so that I could destroy them when I reshuffle the grid in order to make room for the new images (but I probably messed up the instructions).
         If the "drawCell" function only returns a sprite rather than the image array itself, doesn't that mean that my "eraseCells" function won't be able to delete the array's children as their values weren't first returned to the global variable which my erasing function is accessing?
         As for the function name "drawCells," you have to keep in mind that a) my program has been redesigned in stages as I add new functionality/remove old functionality (such as removing text labels and formatting which were originally in this function) and b) that my program is called "Blanko."
         I will try and attach an Illustrator exported JPG file that contains the image I am using as the class "skin7" just to give you an example of what I'm trying to use as labels (although it won't let me insert it here in this post, so I will try it in the next post).
    Thank you for your help!

Maybe you are looking for

  • XY-Graph / Plot legend: How to detect changes in 2nd/3rd/4th ... legend position

    Hello, I have an XY-Graph with 4 plots. How can I detect, for example, the color change of the second plot in the legend. The active plot, using a property node, is always plot 0. So I am not able to detect changes in the 2nd/3rd ... plot. Any ideas?

  • How to execute a stored procedure with an out parameter ?

    Guys I am struggling with executing a stored procedure from sql plus.I mean my stored procedure has 2 input parameter and 1 out put parameter (status of the execution). MY_PROCEDURE(p_name in varchar2,p_age in number,p_status out varchar2) end my_pro

  • First Time Making A Call With Skype

    I just bought Skype credit to start making calls for the first time. In the account section I was asked to check my mobile phone for the information code and enter it below. But I need help for what my mobile phone information code is. James Kwegir A

  • Hard time with "controlling speed along a motion path"

    Actually I have hard time understanding the description of this topic, page 776, chapter 48 of the user manual. I have been able to create 2 keyframes in my clip. But when it comes to adding Bezier Handles it becomes very tricky. By Control-clicking

  • Belkin wireless router connected but browser could not find the host server

    my new roommate has a belkin n wireless router connected to a cable modem which functions perfectly on her pc laptop. i am trying to connect my MacBook Pro to the router using her WEP password. this all works fine and my System Preferences/Network/St