Loading and modifying dynamic bitmap data in ActionScript 3/Flex 3
Posted by Ian Serlin | Tweet This | Filed under Actionscript 3, Adobe Flex, problem solution
If you are loading images dynamically using a Flex 3 Image control and attempting to manipulate the actual bitmap data, say for instance to draw a reflection or auto-center an image, you might have encountered the following runtime exception: “SecurityError: Error #2123: Security sandbox violation: Loader.content: … No policy files granted access.”
This has to do with Flash Player security settings, but thankfully there is a way around this silliness if you check into the docs, but you’ll have to access the Flex private APIs in order to do so.
Problem
You want to manipulate dynamically loaded bitmap data.
Solution
The following class, which is a drop-in replacement for the Flex 3 image class handles setting the appropriate permissions on the Image class’s internal Loader for you and also turns on smoothing by default just for convenience.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package components { import flash.display.Bitmap; import flash.display.Loader; import flash.events.Event; import flash.system.LoaderContext; import mx.controls.Image; import mx.core.mx_internal; use namespace mx_internal; public class PolicyCheckingImage extends Image { public function PolicyCheckingImage() { super(); this.loaderContext = new LoaderContext( true ); } /** * @private */ override mx_internal function contentLoaderInfo_completeEventHandler(event:Event):void { var smoothLoader:Loader = event.target.loader as Loader; var smoothImage:Bitmap = smoothLoader.content as Bitmap; smoothImage.smoothing = true; super.contentLoaderInfo_completeEventHandler(event); } } } |
There are obviously fancier things to do with loaded images, but I’m sure you can find a good reflection implementation elsewhere. My hope is that this saves you a few minutes of time.
If you have bad ass Image classes or the above doesn’t solve your problem in some instances write it up and let me know in the comments!