Recipe 8.4. Loading an
External Image into a Bitmap
Problem
You want
to load an external bitmap image
and manipulate it as a BitmapData.
Solution
Use the flash.display.Loader class to
load the image. When the image has loaded, access the loader's
content property,
which is a Bitmap. Accessing that Bitmap's
bitmapData property gives you direct access to the
BitmapData representing the loaded image.
Discussion
You load an external bitmap image via the
Loader class. This
takes a URLRequest object with the URL of the image you are
loading. Listening for the loader's complete event lets you
know when the image has loaded. Here is the setup to create the
loaderlisten for the complete event and begin loading an
image:
package {
import flash.display.Sprite;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
public class BitmapLoader extends Sprite {
private var _loader:Loader = new Loader( );
public function BitmapLoader( ) {
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_loader.load(new URLRequest("image.jpg"));
}
}
}
By itself, this code simply loads and displays
the specified image. Next, create the onComplete method
that accesses the bitmap information once it has loaded:
public function onComplete(event:Event):void {
var image:Bitmap = Bitmap(_loader.content);
var bitmap:BitmapData = image.bitmapData;
addChild(image);
}
First, get a reference to the loader's content
property. This is a display object representing the content that
was loaded. If you have loaded an external .swf, it is a
MovieClip type. In this case, however, you have loaded a
bitmap image, so the content contains a Bitmap. You should
cast it as a Bitmap so the compiler doesn't complain when
you try to access properties that belong only to Bitmap.
Next, you can access the BitmapData
contained within the Bitmap by reading its BitmapData property. This gives
you the ability to modify and manipulate the newly loaded image.
This example draws a white square on the image.
Alternately, you could draw the loaded image
into a new BitmapData and display that.
public function onComplete(event:Event):void {
var loadedImage:Bitmap = Bitmap(_loader.content);
// Create a new Bitmap data and draw the
// loaded image to it.
var bitmap:BitmapData = new BitmapData(loadedImage.width,
loadedImage.height,
false, 0xffffffff);
bitmap.draw(loadedImage, new Matrix( ))
// Create a new Bitmap using the BitmapData
// and display it.
var image:Bitmap = new Bitmap(bitmap);
addChild(image);
// Manipulate the pixels as you wish
bitmap.fillRect(new Rectangle(0, 0, 50, 50), 0xffffffff);
}
See Also
Recipe
8.1 for how to create a bitmap and Recipe
8.2 for information on how to make a BitmapData
visible.
|