0
votes

Using AS3 and AIR I'd like to get image dimensions after loading them in with ByteArray. Using the code below I can manage to load the images ok and even apply scaleX/scaleY successfully but get zero as height/width from the loader size.

        private function listFiles():void{
        imagesPath=layout.pathFld.text;
        fileList=new Array;
        var desktop:File = File.userDirectory.resolvePath(imagesPath);
        var files:Array = desktop.getDirectoryListing();
        for (var i:uint = 0; i < files.length; i++)
        {
            fileList.push(files[i].nativePath);
        }
        for (i = 0; i < fileList.length; i++)
        {
            layout.txtFld.appendText(fileList[i]+"\n");
        }
        loadOneImage();
    }

    private function loadOneImage():void
    {
        var f:String=fileList[counter];
        bytes = new ByteArray();
         myFileStream = new FileStream();
        var myFile:File = File.userDirectory.resolvePath(f);

        myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
        myFileStream.addEventListener(Event.COMPLETE, loadImage);       
        myFileStream.openAsync(myFile, FileMode.READ);
    }

    private function progressHandler(event:ProgressEvent):void 
    {
        if (myFileStream.bytesAvailable)
        {
            myFileStream.readBytes(bytes, myFileStream.position, myFileStream.bytesAvailable);
        }
    }

    private function loadImage(e:Event):void
    {
        var loader:Loader = new Loader();
        loader.loadBytes(bytes);    
        loader.scaleX=.05;
        loader.scaleY=.05;
        var ph:Number=loader.height;
        var pw:Number=loader.width;
        trace("ph/pw="+ph+"/"+pw);
       // I GET ZEROS HERE
     }
2

2 Answers

0
votes

To get your image dimensions, you can use Loader.contentLoaderInfo, but as @Vesper said, you have to wait that its Event.COMPLETE event is fired otherwise compiler will fire an error, so you can do like this :

var loader:Loader = new Loader();
    loader.loadBytes(bytes);
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onContentLoad);
    function onContentLoad(e:Event):void{
        trace('image width : ' + e.target.width);
        trace('image height : ' + e.target.height);         
    }

Hope that can help.

0
votes

In order to properly get size of a constructed DisplayObject, add it to stage first. If you don't need to keep it on stage, you add, get size, remove, all in a space of four lines of code. Also, even if you do loadBytes(), the loader performs loading asynchronously, so you still have to listen for Event.COMPLETE prior to trying to get size.