Karl Johnson
My thoughts on the RIA world
Friday April 06, 2007
Working around Security Sandbox errors in Flex when using BitmapData.draw() (effects and such)
This is not something that you hit every day in Flex development, but when you do hit it, boy does it drive you crazy trying to fix it. Well I am here to save you the time! If you are using BitmapData.draw() somewhere in one of your Flex/Flash effects or distortion utils and you have hit a sandbox security error when trying to play your effect on a component that includes a dynamically loaded image from a remote server, here is your fix!
You can use this on an Image control, a SWFLoader, or a Loader. The key here is to set the loaderContext property of your Image. We need to set the loaderContext property, which is null by default, and set its checkPolicyFile flag to true, so we can tell the Image control (well actually the SWFLoader which it extends) to check a policy file prior to trying to load the image. This tells the Flash Player to chill out on the sandbox error and load the image into the bitmap if a crossdomain.xml file is in place on the image serving server.
Here is what the error probably looks something like:
SecurityError: Error #2122: Security sandbox violation: BitmapData.draw: http://localhost/me.swf cannot access http://stuff/me.png. A policy file is required, but the checkPolicyFile flag was not set when this media was loaded. Ø at flash.display::BitmapData/draw()
There are a couple ways of doing this, but be careful about instantiation and initialization timing when doing it. A straightforward, simple way to do this is to just instantiate your loaderContext object and set the checkPolicyFile flag to true on the initialize event of your Image. This context object must be created AND configured before the Image control attempts to load the image from the remote server!!
Image Tag:
<mx:Image id="myImage" initialize="imageInit()"
source="http://otherDomain.com/myImage.png" loaderContext="{loaderContext}">
Script Block: [Bindable]
var loaderContext : LoaderContext;
private function imageInit() : void { loaderContext = new LoaderContext(); loaderContext.checkPolicyFile = true; }
Now if all goes well, you should be able to generate BitMaps in memory of your dynamically loaded media objects at will - and without this annoying little error. Don't try to just throw a try/catch block around your effect call either. That will do nothing but catch and hide the error and prevent the effect from playing. Hope this helps some!
If you have any comments or questions, drop me a line at karl.johnson (at) cynergysystems.com
|<