jeudi 19 novembre 2009

Flex 3 and Actionscript 3 (as3), store, save an image (picture) in a database and use it after

I few times ago I had to develop a Flex/Air application which had to manage pictures and display them in a TileList component.

I had to store the images in a mysql Database and be able to display them after. I took a lot of time to find a good solution, so I'm posting this article maybe it can help others ....

Consequently, to store the images, first you have to let the user chose an image on his computer, here is the function for that :

private function browseForFile(event:MouseEvent):void
{
var file:File = new File();
file.addEventListener(Event.SELECT, file_select);
var imageFilter:FileFilter = new FileFilter("Images", "*.jpg;*.png;*jpeg");

file.browseForOpen("Select an image", [imageFilter]);
}

When the file is selected we load it :

private function file_select(evt:Event):void
{
var file:File = new File(File(evt.currentTarget).nativePath);
fileExtension = file.extension;

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoadPicture);
loader.load(new URLRequest(evt.target.url));

}

And when the file is loaded we encode it and save it in the database :

private function handleLoadPicture(event:Event):void
{
var loader:Loader = Loader(event.target.loader);
var image:Bitmap = Bitmap(loader.content);
var encoder:*;

if ( fileExtension == "jpg" || fileExtension == "jpeg" )
encoder = new JPEGEncoder();
else
encoder = new PNGEncoder();

var bytes:ByteArray = encoder.encode(image.bitmapData);
var imageBytes:String = Base64.encodeByteArray(bytes);
//here you can send your request to the DB to store the "imageBytes" String representing //the image
}

As you would notice before storing the image in the DB I encode the Bytes in Base 64 using a class that you can find here .


Now that the image is stored in the dabase we can load when wanted :

var img:Image = new Image();
img.load(Base64.decodeToByteArray(imageData));
//this.addChild(img);

In this code the "imageData" represents the Bytes string (containing the image's data) requested from the Database.


That's it !

0 commentaires:

Enregistrer un commentaire