Insert image from File System into text using the Text Layout Framework
Monday, March 23rd, 2009For the past few weeks I've been building a Rich Text Editor using the TLF. It's been a great opportunity to dig into it, and I have to say it's mostly been a pleasure. One of the features was to insert images, which turned out to be easy. So dead easy, that I found it cool enough to warrant a blog post.
Once you've created a TextFlow and activated an EditManager (Making the text editable), it takes just 4 steps:
1) Open an OS Dialogue box, wait for the user to select an image file:
-
public function addImage(e:MouseEvent):void {
-
_file_ref = new FileReference();
-
_file_ref.addEventListener( Event.SELECT, handleFileSelect,false,0,true );
-
var filter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
-
_file_ref.browse([filter]);
-
}
2) Load the selected file:
-
protected function handleFileSelect(e:Event):void {
-
_file_ref.removeEventListener( Event.SELECT, handleFileSelect );
-
_file_ref.addEventListener(Event.COMPLETE, handleFileOpen,false,0,true );
-
_file_ref.load();
-
}
3) The file is now in the form of a ByteArray. Use a Loader, to loadBytes() and wait for a COMPLETE event.
-
protected function handleFileOpen(e:Event):void {
-
_file_ref.removeEventListener(Event.COMPLETE, handleFileOpen );
-
var data:ByteArray = _file_ref.data as ByteArray;
-
_img_loader=new Loader();
-
_img_loader.loadBytes(data);
-
_img_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,imageLoadComplete,false,0,true);
-
}
4) Then "copy" the BitmapData into a new Bitmap. This might seem a bit cryptic, a good explanation can be found in this thead Finally, the "one liner" or the "punchline" of this blog post: use EditManager.insertInlineGraphic() to plug it into the textFlow.
-
protected function imageLoadComplete(e:Event):void{
-
_img_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,imageLoadComplete);
-
var bmd:BitmapData=Bitmap(_img_loader.content).bitmapData;
-
var bm:Bitmap=new Bitmap(bmd);
-
EditManager(_flow.interactionManager).insertInlineGraphic(bm,bm.width,bm.height);
-
_flow.flowComposer.updateAllContainers();
-
}
That is all... Well, for this to be useful, the image will have to be stored somewhere, if the document being created is to be saved or sent somewhere.
download the source (just one zipped mxml file)
For further reading, here's a couple useful links concerning the TLF:
How to use the TLF tutorial
TLF online forum
online TLF documentation













