Cropping white space from images using Flex Bitmap classes
This blog entry covers a quick introduction to the Flex bitmap classes, BitmapData and Bitmap.
Loading an Image
Typically you would load an image in Flex using the Image tag
<mx:Image id="imageContainer" src="myImage.png"/>
In order to modify the image before displaying it, it is better to use a Loader. Remove the src attribute above and use the following functions instead.
public function onCreationComplete():void { var imageURL:String = "myImage.png"; var imageLoader:Loader = new Loader(); imageLoader.contentLoaderInfo.addEventListener( Event.COMPLETE, onImageReady); imageLoader.load(new URLRequest(imageURL)); } public function onImageReady(e:Event):void { var srcBitmapData:BitmapData = e.target.content.bitmapData; var bitmap:Bitmap = new Bitmap(dstBitmapData); imageContainer.source = bitmap; }
Finding the image boundry
The BitmapData class contains a function called getColorBoundsRect which is perfect for detecting the rectangle which surrounds the actual image data. It can return a rectangle that fully encloses all pixels of a specified color within the bitmap image or a rectangle that fully encloses all pixels that do not include the specified color. Since I want to remove the white space, I am going to use the latter and set the findColor input parameter to false.
var bounds:Rectangle = srcBitmapData.getColorBoundsRect(0xFFFFFF,0xFFFFFF,false);
Cropping the image
Next I can use the bounds to copy specific pixels into a new bitmapData object.
var dstBitmapData:BitmapData = new BitmapData(bounds.width,bounds.height); dstBitmapData.copyPixels(srcBitmapData,bounds,new Point(0,0));
And finally, I create a new bitmap object from the new bitmap data and set my image tag source.
var bitmap:Bitmap = new Bitmap(dstBitmapData); flexChartComponent.flexApppliation.image.source = bitmap;
{
if( flexChartComponent.flexApppliation["chartDataProvider"] != null ) {
flexChartComponent.flexApppliation["chartDataProvider"]["source"] = chartData;
//addEventListenerTo( flexChartComponent.flexApppliation, “complete”, imageCompleteHandler );
// set the ImageComponent’s imageURL, which will cause it’s <mx:Image> to load and a “complete” event
//flexChartComponent.flexApppliation.
var imageURL:String =
BootStrapParams.SERVER_URL + “:” + BootStrapParams.SERVER_PORT + “/” + BootStrapParams.SERVER_PATH
+ “/Download?” + data.resourceURL + “/image.png”;
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageCompleteHandler);
imageLoader.load(new URLRequest(imageURL));
}
}