Sunday, April 12, 2009

Flex : How To Create Bitmap From FileReference

Actually, this article has some kind of title, maybe it should be:

  1. How to Convert ByteArray to Bitmap
  2. How to preview Image from file browsed from FileReference browse() method

Why? Because it’s all related to Bitmap, Image and ByteArray. Here’s the story.

Problem & Discussion:

We want to browse a file from our local drive(s), it’s an image file. So, after we choose the Image, we want to preview it. But before going to far, we need to browse it first, here’s the code

var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)", "*.txt; *.rtf");
var allTypes:Array = new Array(imageTypes, textTypes);
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(Event.SELECT, browseSelect);
fileRef.addEventListener(Event.COMPLETE, browseComplete);
var success:Boolean = fileRef.browse(allTypes);

let see, we had a browseSelect() method and browseComplete method().

Here’s the code for browseSelect() method, contain only a single line

function browseSelect(event:Event):void
{
    fileRef.load();
}

What happened after the load() method finished load the file? It will trigger the browseComplete() method, and what will we do there?

function browseComplete(event:Event):void
{
    var loader:Loader = new Loader();            
    loader.contentLoaderInfo.addEventListener
       (Event.COMPLETE,loaderCompleteHandler);
    loader.loadBytes(fileRef.data);


    function loaderCompleteHandler(event:Event):void{
        Alert.show("Complete");
        var loader:Loader = Loader(event.target.loader);;
        var bmp:Bitmap = Bitmap(loader.content);               
        mcPreview.removeChildAt(1);
        mcPreview.addChild(bmp);
    }
}

in the browseComplete() event, we need ask help from Loader class. Actually, we need it’s loadBytes() method. Don’t forget to give a listener to complete event if loadBytes() method completed.

After loadBytes() complete, loaderCompleteHandler() will triggered and as you can see, the “real” Bitmap itself stored in the “event.target.loader”. What i has done in the end of the line is add the Bitmap loaded into a Movie Clip. Getting error adding MovieClip into Flex? Here’s the solution:

var ui:UIComponent = new UIComponent();
ui.addChild(mcPreview);
panelKanan.addChild(ui);

Suppose your MovieClip are called “mcPreview” and you wanted to add it into a Panel. Before you add MovieClip into a Panel, please add your MovieClip into UIComponent first, and then add the UIComponent into Flex’s Panel. It will solve everything 6

No comments:

Post a Comment