actionscript-3actionflash-cs5zip

AS3 Retrieving a file from FZip


I am currently coding a game and I am storing all external files in a zip file to save space.

I am trying to use Fzip to load an image out of the Zip file and display it on stage but I am having no luck.

FZip Site - http://codeazur.com.br/lab/fzip/ Example 1 Site - http://www.tuicool.com/articles/7VfQr2

I have got the zip file to load and return me the number of files inside it but I cannot figure out how to retrieve an image called "test.png".

import deng.fzip.FZip;
import deng.fzip.FZipFile;
import deng.fzip.FZipLibrary;
import flash.display.*; 

var zip:FZip = new FZip();
var loaderzippy:Loader = new Loader();

function unzipObb():void {      
zip.load(new     URLRequest("file://"+File.applicationStorageDirectory.nativePath+"/cake2.zip"​));
zip.addEventListener(Event.OPEN, onOpen);
zip.addEventListener(Event.COMPLETE, dosomething);  }   

function dosomething(evt:Event):void {
trace("dosomething");
var img_file:FZipFile = zip.getFileByName("test.png");
var loaderzip:Loader = new Loader();
loaderzip.loadBytes(img_file.content);

var image:Bitmap = Bitmap(loaderzip.content); 
addChild(image); }

I just get returned #2007: Parameter child must be non-null.

Any help would be great. Thanks.


Solution

  • When you load the PNG bytes using loaderzip.loadBytes(), you need an event listener to check when it's done loading. The documentation itself states:

    The loadBytes() method is asynchronous. You must wait for the "init" event before accessing the properties of a loaded object.

    Because you're trying to access the code directly after you called loadBytes(), at which point it hasn't actually loaded anything, you're getting a null bitmap.

    Although you can access the data once the "init" event has been dispatched, it's best to wait for the "complete" event, since you want your image to be done loading (rather than halfway done). I've tweaked your code to something that should work:

    function dosomething(evt:Event):void {
        trace("dosomething");
        var img_file:FZipFile = zip.getFileByName("test.png");
        var loaderzip:Loader = new Loader();
        loaderzip.contentLoaderInfo.addEventListener(Event.COMPLETE, getImage);
        loaderzip.loadBytes(img_file.content);
    }
    
    function getImage(e:Event):void {
        var loaderInfo:LoaderInfo = e.currentTarget as LoaderInfo;
        var image:Bitmap = Bitmap(loaderInfo.content);
        addChild(image);
    }
    

    (I haven't tested this myself but it's just to give you the general idea anyway.)

    Note that you should add the event listener to loaderzip.contentLoaderInfo, not just loaderzip. That's what actually dispatches the event and it also contains the loaded content.