An MXML Image Component That Loads Images With No Associated Policy Files

In a major UcompOS project I am working on, I am finding the need more and more to load images from various different servers where the destination servers often have no crossdomain.xml policy file.

I don’t want to use a back-end proxy to deal with this as that would be chewing up my back-end resources and bandwidth which goes against my grain especially when targeting a product for wide deployment.

I will post the code of the component below which should be very self-explanatory:

<?xml version="1.0" encoding="utf-8"?>
<mx:Image xmlns:fx="http://ns.adobe.com/mxml/2009" 
		  xmlns:s="library://ns.adobe.com/flex/spark" 
		  xmlns:mx="library://ns.adobe.com/flex/mx" 
		  securityError="securityErrorHandler(event)" 
		  trustContent="true">
	<fx:Script>
		<![CDATA[
 
			private var _legal:Boolean = true; 
			private var _url:String;
 
			public function get legal():Boolean
			{
				return _legal;
			}
 
			private function securityErrorHandler(event:SecurityErrorEvent):void
			{
				this.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);
				_legal = false;
				var sprite:Sprite = new Sprite();
				var loader:Loader = new Loader();
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,load_handler);
				sprite.addChild(loader);
				var loaderContext:LoaderContext = new LoaderContext();
				loaderContext.checkPolicyFile = false;
				loader.load(new URLRequest(url),loaderContext);
			}
 
			private function load_handler(event:Event):void
			{
				var loaderInfo:LoaderInfo = event.target as LoaderInfo;
				loaderInfo.removeEventListener(Event.COMPLETE,load_handler);
				var bitmapData:BitmapData = new BitmapData(loaderInfo.width,loaderInfo.height);
				var matrix:Matrix = new Matrix();
				bitmapData.draw(loaderInfo.content,matrix);
				var bitmap:Bitmap = new Bitmap(bitmapData);
				source = bitmap;
			}
 
			public function get url():String
			{
				return _url;
			}
 
			public function set url(value:String):void
			{
				loaderContext = new LoaderContext(false);
				_url = value;
				source = value;
			}
		]]>
	</fx:Script>
</mx:Image>

Some things to point out about the component in no particular order:

  • You set a value of a URL to the image to the url property instead of the source property
  • A Boolean named legal has a false value if the content of the image was loaded using an assisting Sprite and Loader instance
  • The source property on an Image control is of a wildcard (*) type – if the value of legal is true, then source is a String and will have the same value as url. If the value of legal is false, then source will be an Object of type Bitmap