Posts Tagged ‘BitmapData’

Reusing BitmapData for Multiple Bitmap/Image Objects

Thursday, June 6th, 2013

I was working with Bitmap and BitmapData objects quite a lot recently.

Noticed that it is better to reuse the BitmapData objects for each new Bitmap object that is created, where the underlying pixels will be the same. They can then be manipulated as required separately, but without having multiple instances of the complex BitmapData object.

A code example I was using to check this out, as well as for loading the sample image locally in Air, is given below:

<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 
						creationComplete="creationCompleteHandler(event)" >
	<mx:Script>
		<![CDATA[
			import mx.controls.Image;
			import mx.core.UIComponent;
			import mx.events.FlexEvent;
			private var myTimer:Timer;
			
			private var myBitmapData:BitmapData;
			
			protected function creationCompleteHandler(event:FlexEvent):void
			{
				var urlString:String = "file:///C:/assets/images/client_logo.png";
								
				var req:URLRequest = new URLRequest(urlString);
				var ldr:Loader = new Loader();
				ldr.load(req); 
				ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, fileLoadComplete);
				ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);				
			}
			
			private function onIOError(event:IOErrorEvent):void{
				trace(event.text);
			}
			
			private function fileLoadComplete(event:Event):void
			{
				var ldr:Loader = Loader(event.target.loader);
				var bitmap:Bitmap = Bitmap(ldr.content);
				myBitmapData = bitmap.bitmapData;
				
				displayImage1.source = new Bitmap(myBitmapData);		
				displayImage2.source = new Bitmap(myBitmapData);
			}
			
		]]>
	</mx:Script>	
	<mx:Image id="displayImage1"/>
	<mx:Image id="displayImage2" y="0" x="50"/>
	
</mx:WindowedApplication>

UPDATE

Flash Player 10.1 and AIR 2.5 the reuse of BitmapData among many instances of Bitmap objects is now done automatically, for improved performance.