Packageflash.display
Classpublic class BitmapData
InheritanceBitmapData Inheritance Object
ImplementsIBitmapDrawable

Language version: ActionScript 3.0
Runtime version: AIR 1.0

The BitmapData class lets you work with the data (pixels) of a Bitmap object bitmap image. You can use the methods of the BitmapData class to create arbitrarily sized transparent or opaque bitmap images and manipulate them in various ways at runtime. You can also access the BitmapData for a bitmap image that you load with the flash.display.Loader class.

This class lets you separate bitmap rendering operations from the internal display updating routines of Flash Player. By manipulating a BitmapData object directly, you can create complex images without incurring the per-frame overhead of constantly redrawing the content from vector data.

The methods of the BitmapData class support effects that are not available through the filters available to non-bitmap display objects.

A BitmapData object contains an array of pixel data. This data can represent either a fully opaque bitmap or a transparent bitmap that contains alpha channel data. Either type of BitmapData object is stored as a buffer of 32-bit integers. Each 32-bit integer determines the properties of a single pixel in the bitmap.

Each 32-bit integer is a combination of four 8-bit channel values (from 0 to 255) that describe the alpha transparency and the red, green, and blue (ARGB) values of the pixel. (For ARGB values, the most significant byte represents the alpha channel value, followed by red, green, and blue.)

The four channels (alpha, red, green, and blue) are represented as numbers when you use them with the BitmapData.copyChannel() method or the DisplacementMapFilter.componentX and DisplacementMapFilter.componentY properties, and these numbers are represented by the following constants in the BitmapDataChannel class:

You can attach BitmapData objects to a Bitmap object by using the bitmapData property of the Bitmap object.

You can use a BitmapData object to fill a Graphics object by using the Graphics.beginBitmapFill() method.

In the AIR runtime, the DockIcon, Icon, InteractiveIcon, and SystemTrayIcon classes each include a bitmaps property that is an array of BitmapData objects that define the bitmap images for an icon.

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 in width.

Starting with AIR 3 and Flash player 11, the size limits for a BitmapData object have been removed. The maximum size of a bitmap is now dependent on the operating system.

Calls to any method or property of a BitmapData object throw an ArgumentError error if the BitmapData object is invalid (for example, if it has height == 0 and width == 0) or it has been disposed of via dispose().

View the examples.

See also

flash.display.Bitmap.bitmapData
flash.desktop.DockIcon.bitmaps
flash.display.Graphics.beginBitmapFill()
flash.desktop.Icon.bitmaps
flash.desktop.InteractiveIcon.bitmaps
flash.display.Loader
flash.desktop.SystemTrayIcon.bitmaps


Public Properties
 PropertyDefined by
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  height : int
[read-only] The height of the bitmap image in pixels.
BitmapData
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  rect : Rectangle
[read-only] The rectangle that defines the size and location of the bitmap image.
BitmapData
  transparent : Boolean
[read-only] Defines whether the bitmap image supports per-pixel transparency.
BitmapData
  width : int
[read-only] The width of the bitmap image in pixels.
BitmapData
Public Methods
 MethodDefined by
  
BitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 0xFFFFFFFF)
Creates a BitmapData object with a specified width and height.
BitmapData
  
applyFilter(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, filter:BitmapFilter):void
Takes a source image and a filter object and generates the filtered image.
BitmapData
  
Returns a new BitmapData object that is a clone of the original instance with an exact copy of the contained bitmap.
BitmapData
  
Adjusts the color values in a specified area of a bitmap image by using a ColorTransform object.
BitmapData
  
compare(otherBitmapData:BitmapData):Object
Compares two BitmapData objects.
BitmapData
  
Create a copy of the image data, converting between color profiles based on the provided Screen objects.
BitmapData
  
copyChannel(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, sourceChannel:uint, destChannel:uint):void
Transfers data from one channel of another BitmapData object or the current BitmapData object into a channel of the current BitmapData object.
BitmapData
  
copyPixels(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, alphaBitmapData:BitmapData = null, alphaPoint:Point = null, mergeAlpha:Boolean = false):void
Provides a fast routine to perform pixel manipulation between images with no stretching, rotation, or color effects.
BitmapData
  
Fills a byte array from a rectangular region of pixel data.
BitmapData
  
[static] Decompresses encoded image data (PNG/GIF89a/JPEG) into a new BitmapData object using data provided in a ByteArray.
BitmapData
  
Frees memory that is used to store the BitmapData object.
BitmapData
  
draw(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false):void
Draws the source display object onto the bitmap image, using the Flash runtime vector renderer.
BitmapData
  
drawWithQuality(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false, quality:String = null):void
Draws the source display object onto the bitmap image, using the Flash runtime vector renderer.
BitmapData
  
encode(rect:Rectangle, compressor:Object, byteArray:ByteArray = null):ByteArray
Compresses this BitmapData object using the selected compressor algorithm and returns a new ByteArray object.
BitmapData
  
fillRect(rect:Rectangle, color:uint):void
Fills a rectangular area of pixels with a specified ARGB color.
BitmapData
  
floodFill(x:int, y:int, color:uint):void
Performs a flood fill operation on an image starting at an (x, y) coordinate and filling with a certain color.
BitmapData
  
Determines the destination rectangle that the applyFilter() method call affects, given a BitmapData object, a source rectangle, and a filter object.
BitmapData
  
getColorBoundsRect(mask:uint, color:uint, findColor:Boolean = true):Rectangle
Determines a rectangular region that either fully encloses all pixels of a specified color within the bitmap image (if the findColor parameter is set to true) or fully encloses all pixels that do not include the specified color (if the findColor parameter is set to false).
BitmapData
  
Returns an integer that represents an RGB pixel value from a BitmapData object at a specific point (x, y).
BitmapData
  
Returns an ARGB color value that contains alpha channel data and RGB data.
BitmapData
  
Generates a byte array from a rectangular region of pixel data.
BitmapData
  
Generates a vector array from a rectangular region of pixel data.
BitmapData
 Inherited
Indicates whether an object has a specified property defined.
Object
  
Computes a 256-value binary number histogram of a BitmapData object.
BitmapData
  
hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean
Performs pixel-level hit detection between one bitmap image and a point, rectangle, or other bitmap image.
BitmapData
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are not updated when this BitmapData object changes.
BitmapData
  
merge(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redMultiplier:uint, greenMultiplier:uint, blueMultiplier:uint, alphaMultiplier:uint):void
Performs per-channel blending from a source image to a destination image.
BitmapData
  
noise(randomSeed:int, low:uint = 0, high:uint = 255, channelOptions:uint = 7, grayScale:Boolean = false):void
Fills an image with pixels representing random noise.
BitmapData
  
paletteMap(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redArray:Array = null, greenArray:Array = null, blueArray:Array = null, alphaArray:Array = null):void
Remaps the color channel values in an image that has up to four arrays of color palette data, one for each channel.
BitmapData
  
perlinNoise(baseX:Number, baseY:Number, numOctaves:uint, randomSeed:int, stitch:Boolean, fractalNoise:Boolean, channelOptions:uint = 7, grayScale:Boolean = false, offsets:Array = null):void
Generates a Perlin noise image.
BitmapData
  
pixelDissolve(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, randomSeed:int = 0, numPixels:int = 0, fillColor:uint = 0):int
Performs a pixel dissolve either from a source image to a destination image or by using the same image.
BitmapData
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
  
scroll(x:int, y:int):void
Scrolls an image by a certain (x, y) pixel amount.
BitmapData
  
setPixel(x:int, y:int, color:uint):void
Sets a single pixel of a BitmapData object.
BitmapData
  
setPixel32(x:int, y:int, color:uint):void
Sets the color and alpha transparency values of a single pixel of a BitmapData object.
BitmapData
  
setPixels(rect:Rectangle, inputByteArray:ByteArray):void
Converts a byte array into a rectangular region of pixel data.
BitmapData
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
setVector(rect:Rectangle, inputVector:Vector.<uint>):void
Converts a Vector into a rectangular region of pixel data.
BitmapData
  
threshold(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, operation:String, threshold:uint, color:uint = 0, mask:uint = 0xFFFFFFFF, copySource:Boolean = false):uint
Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values.
BitmapData
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
  
unlock(changeRect:Rectangle = null):void
Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are updated when this BitmapData object changes.
BitmapData
 Inherited
Returns the primitive value of the specified object.
Object
Property detail
heightproperty
height:int  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.0

The height of the bitmap image in pixels.

Implementation
    public function get height():int
rectproperty 
rect:Rectangle  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.0

The rectangle that defines the size and location of the bitmap image. The top and left of the rectangle are 0; the width and height are equal to the width and height in pixels of the BitmapData object.

Implementation
    public function get rect():Rectangle
transparentproperty 
transparent:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Defines whether the bitmap image supports per-pixel transparency. You can set this value only when you construct a BitmapData object by passing in true for the transparent parameter of the constructor. Then, after you create a BitmapData object, you can check whether it supports per-pixel transparency by determining if the value of the transparent property is true.

Implementation
    public function get transparent():Boolean
widthproperty 
width:int  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 1.0

The width of the bitmap image in pixels.

Implementation
    public function get width():int
Constructor detail
BitmapData()constructor
public function BitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 0xFFFFFFFF)

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Creates a BitmapData object with a specified width and height. If you specify a value for the fillColor parameter, every pixel in the bitmap is set to that color.

By default, the bitmap is created as transparent, unless you pass the value false for the transparent parameter. After you create an opaque bitmap, you cannot change it to a transparent bitmap. Every pixel in an opaque bitmap uses only 24 bits of color channel information. If you define the bitmap as transparent, every pixel uses 32 bits of color channel information, including an alpha transparency channel.

In AIR 1.5 and Flash Player 10, the maximum size for a BitmapData object is 8,191 pixels in width or height, and the total number of pixels cannot exceed 16,777,215 pixels. (So, if a BitmapData object is 8,191 pixels wide, it can only be 2,048 pixels high.) In Flash Player 9 and earlier and AIR 1.1 and earlier, the limitation is 2,880 pixels in height and 2,880 pixels in width. If you specify a width or height value that is greater than 2880, a new instance is not created.

Parameters
width:int — The width of the bitmap image in pixels.
 
height:int — The height of the bitmap image in pixels.
 
transparent:Boolean (default = true) — Specifies whether the bitmap image supports per-pixel transparency. The default value is true (transparent). To create a fully transparent bitmap, set the value of the transparent parameter to true and the value of the fillColor parameter to 0x00000000 (or to 0). Setting the transparent property to false can result in minor improvements in rendering performance.
 
fillColor:uint (default = 0xFFFFFFFF) — A 32-bit ARGB color value that you use to fill the bitmap image area. The default value is 0xFFFFFFFF (solid white).

Throws
ArgumentError — width and/or height exceed the maximum dimensions.
Method detail
applyFilter()method
public function applyFilter(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, filter:BitmapFilter):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Takes a source image and a filter object and generates the filtered image.

This method relies on the behavior of built-in filter objects, which determine the destination rectangle that is affected by an input source rectangle.

After a filter is applied, the resulting image can be larger than the input image. For example, if you use a BlurFilter class to blur a source rectangle of (50,50,100,100) and a destination point of (10,10), the area that changes in the destination image is larger than (10,10,60,60) because of the blurring. This happens internally during the applyFilter() call.

If the sourceRect parameter of the sourceBitmapData parameter is an interior region, such as (50,50,100,100) in a 200 x 200 image, the filter uses the source pixels outside the sourceRect parameter to generate the destination rectangle.

If the BitmapData object and the object specified as the sourceBitmapData parameter are the same object, the application uses a temporary copy of the object to perform the filter. For best performance, avoid this situation.

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData instance.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle.
 
filter:BitmapFilter — The filter object that you use to perform the filtering operation. Each type of filter has certain requirements, as follows:
  • BlurFilter — This filter can use source and destination images that are either opaque or transparent. If the formats of the images do not match, the copy of the source image that is made during the filtering matches the format of the destination image.
  • BevelFilter, DropShadowFilter, GlowFilter — The destination image of these filters must be a transparent image. Calling DropShadowFilter or GlowFilter creates an image that contains the alpha channel data of the drop shadow or glow. It does not create the drop shadow onto the destination image. If you use any of these filters with an opaque destination image, an exception is thrown.
  • ConvolutionFilter — This filter can use source and destination images that are either opaque or transparent.
  • ColorMatrixFilter — This filter can use source and destination images that are either opaque or transparent.
  • DisplacementMapFilter — This filter can use source and destination images that are either opaque or transparent, but the source and destination image formats must be the same.

Throws
TypeError — The sourceBitmapData, sourceRect, destPoint or filter are null.
 
Error — The transparency of the BitmapData objects are not compatible with the filter operation.

See also


Example
The following example shows how to apply a blur filter to a BitmapData instance:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.filters.BlurFilter;

var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00);
var rect:Rectangle = new Rectangle(10, 10, 40, 10);
bmd.fillRect(rect, 0xFF0000);

var pt:Point = new Point(10, 10);
var filter:BlurFilter = new BlurFilter();
bmd.applyFilter(bmd, rect, pt, filter);

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

clone()method 
public function clone():BitmapData

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Returns a new BitmapData object that is a clone of the original instance with an exact copy of the contained bitmap.

Returns
BitmapData — A new BitmapData object that is identical to the original.

Example
The following example shows how to clone a BitmapData instance, and it shows that when you modify the cloned BitmapData instance, the original remains unmodified:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd1:BitmapData = new BitmapData(100, 80, false, 0x00000000);
var bmd2:BitmapData = bmd1.clone();

bmd1.setPixel32(1, 1, 0xFFFFFFFF);

trace(bmd1.getPixel32(1, 1).toString(16)); // ffffffff
trace(bmd2.getPixel32(1, 1).toString(16)); // ff000000

var bm1:Bitmap = new Bitmap(bmd1);
this.addChild(bm1);

var bm2:Bitmap = new Bitmap(bmd2);
bm2.x = 110;
this.addChild(bm2);

colorTransform()method 
public function colorTransform(rect:Rectangle, colorTransform:ColorTransform):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Adjusts the color values in a specified area of a bitmap image by using a ColorTransform object. If the rectangle matches the boundaries of the bitmap image, this method transforms the color values of the entire image.

Parameters
rect:Rectangle — A Rectangle object that defines the area of the image in which the ColorTransform object is applied.
 
colorTransform:ColorTransform — A ColorTransform object that describes the color transformation values to apply.

Throws
TypeError — The rect or colorTransform are null.

See also


Example
The following example shows how to apply a color transform to the left half (rectangle) of a BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.ColorTransform;

var bmd:BitmapData = new BitmapData(80, 30, false, 0xFF0000);

var cTransform:ColorTransform = new ColorTransform();
cTransform.alphaMultiplier = 0.5
var rect:Rectangle = new Rectangle(0, 0, 40, 30);
bmd.colorTransform(rect, cTransform);

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

compare()method 
public function compare(otherBitmapData:BitmapData):Object

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Compares two BitmapData objects. If the two BitmapData objects have the same dimensions (width and height), the method returns a new BitmapData object, in which each pixel is the "difference" between the pixels in the two source objects:

For example, consider the following two BitmapData objects:


     var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFF8800);

     var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCCC6600);

     var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData;

     trace ("0x" + diffBmpData.getPixel(0,0).toString(16); // 0x332200

     

     var bmd1 = new air.BitmapData(50, 50, true, 0xFFFF0000);

     var bmd2 = new air.BitmapData(50, 50, true, 0xCCFFAA00);

     var diffBmpData = bmd1.compare(bmd2);

     

Note: The colors used to fill the two BitmapData objects have slightly different RGB values (0xFF0000 and 0xFFAA00). The result of the compare() method is a new BitmapData object with each pixel showing the difference in the RGB values between the two bitmaps.

Consider the following two BitmapData objects, in which the RGB colors are the same, but the alpha values are different:


     var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00);

     var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00);

     var diffBmpData:BitmapData = bmd1.compare(bmd2) as BitmapData;

     trace ("0x" + diffBmpData.getPixel32(0,0).toString(16); // 0x33ffffff

     

     var bmd1 = new air.BitmapData(50, 50, true, 0xFFFFAA00);

     var bmd2 = new air.BitmapData(50, 50, true, 0xCCFFAA00);

     var diffBmpData = bmd1.compare(bmd2);

     

The result of the compare() method is a new BitmapData object with each pixel showing the difference in the alpha values between the two bitmaps.

If the BitmapData objects are equivalent (with the same width, height, and identical pixel values), the method returns the number 0.

If the widths of the BitmapData objects are not equal, the method returns the number -3.

If the heights of the BitmapData objects are not equal, but the widths are the same, the method returns the number -4.

The following example compares two Bitmap objects with different widths (50 and 60):


     var bmd1:BitmapData = new BitmapData(100, 50, false, 0xFFFF0000);

     var bmd2:BitmapData = new BitmapData(100, 60, false, 0xFFFFAA00);

     trace(bmd1.compare(bmd2)); // -4

     

     var bmd1 = new air.BitmapData(100, 50, false, 0xFFFF0000);

     var bmd2 = new air.BitmapData(100, 60, false, 0xFFFFAA00);

     trace(bmd1.compare(bmd2)); // -4

     
Parameters
otherBitmapData:BitmapData — The BitmapData object to compare with the source BitmapData object.

Returns
Object — If the two BitmapData objects have the same dimensions (width and height), the method returns a new BitmapData object that has the difference between the two objects (see the main discussion). If the BitmapData objects are equivalent, the method returns the number 0. If the widths of the BitmapData objects are not equal, the method returns the number -3. If the heights of the BitmapData objects are not equal, the method returns the number -4.

Throws
TypeError — The otherBitmapData is null.

Example
The following example shows the value of a pixel in the BitmapData object that results from comparing two BitmapData objects of the same dimensions:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd1:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00);
var bmd2:BitmapData = new BitmapData(50, 50, true, 0xCCFFAA00);
var diffBmpData:BitmapData = BitmapData(bmd1.compare(bmd2));
var diffValue:String = diffBmpData.getPixel32(1, 1).toString(16);
trace (diffValue); // 33ffffff

var bm1:Bitmap = new Bitmap(bmd1);
addChild(bm1);
var bm2:Bitmap = new Bitmap(bmd2);
addChild(bm2);
bm2.x = 60;

convertColorProfile()method 
public function convertColorProfile(source:Screen, destination:Screen):BitmapData

Language version: ActionScript 3.0
Runtime version: AIR 51.0

Create a copy of the image data, converting between color profiles based on the provided Screen objects.

To convert a normal/loaded image (in sRGB color profile) so that it is displayed properly on a display, pass in null for the source screen and the application's display location as the destination screen. This would be the normal use case for this feature.

Parameters
source:Screen — A Screen object that will be used to obtain the source color profile. If null, sRGB will be assumed.
 
destination:Screen — A Screen object that will be used to obtain the destination color profile. If null, sRGB will be assumed.

Returns
BitmapData — A new BitmapData object with the appropriate color transformation.
copyChannel()method 
public function copyChannel(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, sourceChannel:uint, destChannel:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Transfers data from one channel of another BitmapData object or the current BitmapData object into a channel of the current BitmapData object. All of the data in the other channels in the destination BitmapData object are preserved.

The source channel value and destination channel value can be one of following values:

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData object.
 
sourceRect:Rectangle — The source Rectangle object. To copy only channel data from a smaller area within the bitmap, specify a source rectangle that is smaller than the overall size of the BitmapData object.
 
destPoint:Point — The destination Point object that represents the upper-left corner of the rectangular area where the new channel data is placed. To copy only channel data from one area to a different area in the destination image, specify a point other than (0,0).
 
sourceChannel:uint — The source channel. Use a value from the BitmapDataChannel class (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA).
 
destChannel:uint — The destination channel. Use a value from the BitmapDataChannel class (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, BitmapDataChannel.ALPHA).

Throws
TypeError — The sourceBitmapData, sourceRect or destPoint are null.

See also


Example
The following example shows how to copy the red channel in a BitmapData object to its own blue channel in a 20 x 20 pixel region:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

var bmd:BitmapData = new BitmapData(100, 80, false, 0x00FF0000);

var rect:Rectangle = new Rectangle(0, 0, 20, 20);
var pt:Point = new Point(10, 10);
bmd.copyChannel(bmd, rect, pt, BitmapDataChannel.RED, BitmapDataChannel.BLUE);

var bm:Bitmap = new Bitmap(bmd);
this.addChild(bm);

copyPixels()method 
public function copyPixels(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, alphaBitmapData:BitmapData = null, alphaPoint:Point = null, mergeAlpha:Boolean = false):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Provides a fast routine to perform pixel manipulation between images with no stretching, rotation, or color effects. This method copies a rectangular area of a source image to a rectangular area of the same size at the destination point of the destination BitmapData object.

If you include the alphaBitmap and alphaPoint parameters, you can use a secondary image as an alpha source for the source image. If the source image has alpha data, both sets of alpha data are used to composite pixels from the source image to the destination image. The alphaPoint parameter is the point in the alpha image that corresponds to the upper-left corner of the source rectangle. Any pixels outside the intersection of the source image and alpha image are not copied to the destination image.

The mergeAlpha property controls whether or not the alpha channel is used when a transparent image is copied onto another transparent image. To copy pixels with the alpha channel data, set the mergeAlpha property to true. By default, the mergeAlpha property is false.

Parameters
sourceBitmapData:BitmapData — The input bitmap image from which to copy pixels. The source image can be a different BitmapData instance, or it can refer to the current BitmapData instance.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The destination point that represents the upper-left corner of the rectangular area where the new pixels are placed.
 
alphaBitmapData:BitmapData (default = null) — A secondary, alpha BitmapData object source.
 
alphaPoint:Point (default = null) — The point in the alpha BitmapData object source that corresponds to the upper-left corner of the sourceRect parameter.
 
mergeAlpha:Boolean (default = false) — To use the alpha channel, set the value to true. To copy pixels with no alpha channel, set the value to false.

Throws
TypeError — The sourceBitmapData, sourceRect, destPoint are null.

Example
The following example shows how to copy pixels from a 20 x 20 pixel region in one BitmapData object to another BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

var bmd1:BitmapData = new BitmapData(40, 40, false, 0x000000FF);
var bmd2:BitmapData = new BitmapData(80, 40, false, 0x0000CC44);

var rect:Rectangle = new Rectangle(0, 0, 20, 20);
var pt:Point = new Point(10, 10);
bmd2.copyPixels(bmd1, rect, pt);

var bm1:Bitmap = new Bitmap(bmd1);
this.addChild(bm1);
var bm2:Bitmap = new Bitmap(bmd2);
this.addChild(bm2);
bm2.x = 50;

copyPixelsToByteArray()method 
public function copyPixelsToByteArray(rect:Rectangle, data:ByteArray):void

Language version: ActionScript 3.0
Runtime version: AIR 3.4

Fills a byte array from a rectangular region of pixel data. Starting at the position index of the ByteArray, this method writes an unsigned integer (a 32-bit unmultiplied pixel value) for each pixel into the byte array. If necessary, the byte array's size is increased to the necessary number of bytes to hold all the pixel data.

Parameters
rect:Rectangle — A rectangular area in the current BitmapData object
 
data:ByteArray — the destination ByteArray object

Throws
TypeError — if the rect argument is null or the data argument is null

See also

decode()method 
public static function decode(data:ByteArray):BitmapData

Language version: ActionScript 3.0
Runtime version: AIR 50.0

Decompresses encoded image data (PNG/GIF89a/JPEG) into a new BitmapData object using data provided in a ByteArray. The image format is determined by the runtime and supports the same formats as can be provided within a SWF file's DefineBitsJPEG2 tag.

Parameters
data:ByteArray — The ByteArray object containing the compressed image data

Returns
BitmapData — A BitmapData containing the decoded image.
dispose()method 
public function dispose():void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Frees memory that is used to store the BitmapData object.

When the dispose() method is called on an image, the width and height of the image are set to 0. All subsequent calls to methods or properties of this BitmapData instance fail, and an exception is thrown.

BitmapData.dispose() releases the memory occupied by the actual bitmap data, immediately (a bitmap can consume up to 64 MB of memory). After using BitmapData.dispose(), the BitmapData object is no longer usable and the Flash runtime throws an exception if you call functions on the BitmapData object. However, BitmapData.dispose() does not garbage collect the BitmapData object (approximately 128 bytes); the memory occupied by the actual BitmapData object is released at the time the BitmapData object is collected by the garbage collector.

See also


Example
The following example shows the effect of calling a method of a BitmapData object after a call to the dispose() method (an exception is thrown):
import flash.display.BitmapData;

var myBitmapData:BitmapData = new BitmapData(100, 80, false, 0x000000FF);
trace(myBitmapData.getPixel(1, 1)); // 255 == 0xFF

myBitmapData.dispose();
try {
    trace(myBitmapData.getPixel(1, 1));
} catch (error:Error) {
	trace(error); // ArgumentError
}

draw()method 
public function draw(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Draws the source display object onto the bitmap image, using the Flash runtime vector renderer. You can specify matrix, colorTransform, blendMode, and a destination clipRect parameter to control how the rendering performs. Optionally, you can specify whether the bitmap should be smoothed when scaled (this works only if the source object is a BitmapData object).

Note: The drawWithQuality() method works exactly like the draw() method, but instead of using the Stage.quality property to determine the quality of vector rendering, you specify the quality parameter to the drawWithQuality() method.

This method directly corresponds to how objects are drawn with the standard vector renderer for objects in the authoring tool interface.

The source display object does not use any of its applied transformations for this call. It is treated as it exists in the library or file, with no matrix transform, no color transform, and no blend mode. To draw a display object (such as a movie clip) by using its own transform properties, you can copy its transform property object to the transform property of the Bitmap object that uses the BitmapData object.

This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess and Client.videoSampleAccess properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server.

If the source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method, a call to the draw() throws a SecurityError exception. This restriction does not apply to AIR content in the application security sandbox.

There are also restrictions on using a loaded bitmap image as the source. A call to the draw() method is successful if the loaded image comes from the same domain as the caller. Also, a cross-domain policy file on the image's server can grant permission to the domain of the SWF content calling the draw() method. In this case, you must set the checkPolicyFile property of a LoaderContext object, and use this object as the context parameter when calling the load() method of the Loader object used to load the image. These restrictions do not apply to AIR content in the application security sandbox.

On Windows, the draw() method cannot capture SWF content embedded in an HTML page in an HTMLLoader object in Adobe AIR.

The draw() method cannot capture PDF content in Adobe AIR. Nor can it capture or SWF content embedded in HTML in which the wmode attribute is set to "window" in Adobe AIR.

Parameters
source:IBitmapDrawable — The display object or BitmapData object to draw to the BitmapData object. (The DisplayObject and BitmapData classes implement the IBitmapDrawable interface.)
 
matrix:Matrix (default = null) — A Matrix object used to scale, rotate, or translate the coordinates of the bitmap. If you do not want to apply a matrix transformation to the image, set this parameter to an identity matrix, created with the default new Matrix() constructor, or pass a null value.
 
colorTransform:ColorTransform (default = null) — A ColorTransform object that you use to adjust the color values of the bitmap. If no object is supplied, the bitmap image's colors are not transformed. If you must pass this parameter but you do not want to transform the image, set this parameter to a ColorTransform object created with the default new ColorTransform() constructor.
 
blendMode:String (default = null) — A string value, from the flash.display.BlendMode class, specifying the blend mode to be applied to the resulting bitmap.
 
clipRect:Rectangle (default = null) — A Rectangle object that defines the area of the source object to draw. If you do not supply this value, no clipping occurs and the entire source object is drawn.
 
smoothing:Boolean (default = false) — A Boolean value that determines whether a BitmapData object is smoothed when scaled or rotated, due to a scaling or rotation in the matrix parameter. The smoothing parameter only applies if the source parameter is a BitmapData object. With smoothing set to false, the rotated or scaled BitmapData image can appear pixelated or jagged. For example, the following two images use the same BitmapData object for the source parameter, but the smoothing parameter is set to true on the left and false on the right:

Two images: the left one with smoothing and the right one without smoothing.

Drawing a bitmap with smoothing set to true takes longer than doing so with smoothing set to false.


Throws
ArgumentError — The source parameter is not a BitmapData or DisplayObject object.
 
SecurityError — The source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method. This restriction does not apply to AIR content in the application security sandbox.
 
ArgumentError — The source is null or not a valid IBitmapDrawable object.

See also


Example
The following example shows how to draw a TextField object to a BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.text.TextField;

var tf:TextField = new TextField();
tf.text = "bitmap text";

var myBitmapData:BitmapData = new BitmapData(80, 20);
myBitmapData.draw(tf);
var bmp:Bitmap = new Bitmap(myBitmapData);
this.addChild(bmp);

drawWithQuality()method 
public function drawWithQuality(source:IBitmapDrawable, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:String = null, clipRect:Rectangle = null, smoothing:Boolean = false, quality:String = null):void

Language version: ActionScript 3.0
Runtime version: AIR 3.3

Draws the source display object onto the bitmap image, using the Flash runtime vector renderer. You can specify matrix, colorTransform, blendMode, and a destination clipRect parameter to control how the rendering performs. Optionally, you can specify whether the bitmap should be smoothed when scaled (this works only if the source object is a BitmapData object).

Note: The drawWithQuality() method works exactly like the draw() method, but instead of using the Stage.quality property to determine the quality of vector rendering, you specify the quality parameter to the drawWithQuality() method.

This method directly corresponds to how objects are drawn with the standard vector renderer for objects in the authoring tool interface.

The source display object does not use any of its applied transformations for this call. It is treated as it exists in the library or file, with no matrix transform, no color transform, and no blend mode. To draw a display object (such as a movie clip) by using its own transform properties, you can copy its transform property object to the transform property of the Bitmap object that uses the BitmapData object.

This method is supported over RTMP in Flash Player 9.0.115.0 and later and in Adobe AIR. You can control access to streams on Flash Media Server in a server-side script. For more information, see the Client.audioSampleAccess and Client.videoSampleAccess properties in Server-Side ActionScript Language Reference for Adobe Flash Media Server.

If the source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method, a call to the drawWithQuality() throws a SecurityError exception. This restriction does not apply to AIR content in the application security sandbox.

There are also restrictions on using a loaded bitmap image as the source. A call to the drawWithQuality() method is successful if the loaded image comes from the same domain as the caller. Also, a cross-domain policy file on the image's server can grant permission to the domain of the SWF content calling the drawWithQuality() method. In this case, you must set the checkPolicyFile property of a LoaderContext object, and use this object as the context parameter when calling the load() method of the Loader object used to load the image. These restrictions do not apply to AIR content in the application security sandbox.

On Windows, the drawWithQuality() method cannot capture SWF content embedded in an HTML page in an HTMLLoader object in Adobe AIR.

The drawWithQuality() method cannot capture PDF content in Adobe AIR. Nor can it capture or SWF content embedded in HTML in which the wmode attribute is set to "window" in Adobe AIR.

Parameters
source:IBitmapDrawable — The display object or BitmapData object to draw to the BitmapData object. (The DisplayObject and BitmapData classes implement the IBitmapDrawable interface.)
 
matrix:Matrix (default = null) — A Matrix object used to scale, rotate, or translate the coordinates of the bitmap. If you do not want to apply a matrix transformation to the image, set this parameter to an identity matrix, created with the default new Matrix() constructor, or pass a null value.
 
colorTransform:ColorTransform (default = null) — A ColorTransform object that you use to adjust the color values of the bitmap. If no object is supplied, the bitmap image's colors are not transformed. If you must pass this parameter but you do not want to transform the image, set this parameter to a ColorTransform object created with the default new ColorTransform() constructor.
 
blendMode:String (default = null) — A string value, from the flash.display.BlendMode class, specifying the blend mode to be applied to the resulting bitmap.
 
clipRect:Rectangle (default = null) — A Rectangle object that defines the area of the source object to draw. If you do not supply this value, no clipping occurs and the entire source object is drawn.
 
smoothing:Boolean (default = false) — A Boolean value that determines whether a BitmapData object is smoothed when scaled or rotated, due to a scaling or rotation in the matrix parameter. The smoothing parameter only applies if the source parameter is a BitmapData object. With smoothing set to false, the rotated or scaled BitmapData image can appear pixelated or jagged. For example, the following two images use the same BitmapData object for the source parameter, but the smoothing parameter is set to true on the left and false on the right:

Two images: the left one with smoothing and the right one without smoothing.

Drawing a bitmap with smoothing set to true takes longer than doing so with smoothing set to false.

 
quality:String (default = null) — Any of one of the StageQuality values. Selects the antialiasing quality to be used when drawing vectors graphics.

Throws
ArgumentError — The source parameter is not a BitmapData or DisplayObject object.
 
SecurityError — The source object and (in the case of a Sprite or MovieClip object) all of its child objects do not come from the same domain as the caller, or are not in a content that is accessible to the caller by having called the Security.allowDomain() method. This restriction does not apply to AIR content in the application security sandbox.
 
ArgumentError — The source is null or not a valid IBitmapDrawable object.

See also


Example
The following example shows how to draw a TextField object to a BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.text.TextField;

var tf:TextField = new TextField();
tf.text = "bitmap text";

var myBitmapData:BitmapData = new BitmapData(80, 20);
myBitmapData.drawWithQuality(tf, , , , , , StageQuality.LOW);
var bmp:Bitmap = new Bitmap(myBitmapData);
this.addChild(bmp);

encode()method 
public function encode(rect:Rectangle, compressor:Object, byteArray:ByteArray = null):ByteArray

Language version: ActionScript 3.0
Runtime version: AIR 3.3

Compresses this BitmapData object using the selected compressor algorithm and returns a new ByteArray object. Optionally, writes the resulting data to the specified ByteArray. The compressor argument specifies the encoding algorithm, and can be PNGEncoderOptions, JPEGEncoderOptions, or JPEGXREncoderOptions.

The following example compresses a BitmapData object using the JPEGEncoderOptions:


     // Compress a BitmapData object as a JPEG file.

     var bitmapData:BitmapData = new BitmapData(640,480,false,0x00FF00);

     var byteArray:ByteArray = new ByteArray();

     bitmapData.encode(new Rectangle(0,0,640,480), new flash.display.JPEGEncoderOptions(), byteArray); 
Parameters
rect:Rectangle — The area of the BitmapData object to compress.
 
compressor:Object — The compressor type to use. Valid values are: flash.display.PNGEncoderOptions, flash.display.JPEGEncoderOptions, and flash.display.JPEGXREncoderOptions.
 
byteArray:ByteArray (default = null) — The output ByteArray to hold the encoded image.

Returns
ByteArray — A ByteArray containing the encoded image.

See also

fillRect()method 
public function fillRect(rect:Rectangle, color:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Fills a rectangular area of pixels with a specified ARGB color.

Parameters
rect:Rectangle — The rectangular area to fill.
 
color:uint — The ARGB color value that fills the area. ARGB colors are often specified in hexadecimal format; for example, 0xFF336699.

Throws
TypeError — The rect is null.

See also


Example
The following example shows how to fill a rectangular region of a BitmapData object with blue:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;

var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00);

var rect:Rectangle = new Rectangle(0, 0, 20, 20);
myBitmapData.fillRect(rect, 0x0000FF);

var bm:Bitmap = new Bitmap(myBitmapData);
addChild(bm);

floodFill()method 
public function floodFill(x:int, y:int, color:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Performs a flood fill operation on an image starting at an (x, y) coordinate and filling with a certain color. The floodFill() method is similar to the paint bucket tool in various paint programs. The color is an ARGB color that contains alpha information and color information.

Parameters
x:int — The x coordinate of the image.
 
y:int — The y coordinate of the image.
 
color:uint — The ARGB color to use as a fill.

Example
The following example shows how to fill a region of a BitmapData object — that is, the region surrounding the pixel defined by the point (10, 10) in which all colors match the color at that point — with red

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;

var myBitmapData:BitmapData = new BitmapData(40, 40, false, 0x0000FF00);

var rect:Rectangle = new Rectangle(0, 0, 20, 20);
myBitmapData.fillRect(rect, 0x000000FF);
rect = new Rectangle(15, 15, 25, 25);
myBitmapData.fillRect(rect, 0x000000FF);

myBitmapData.floodFill(10, 10, 0x00FF0000);

var bm:Bitmap = new Bitmap(myBitmapData);
addChild(bm);

generateFilterRect()method 
public function generateFilterRect(sourceRect:Rectangle, filter:BitmapFilter):Rectangle

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Determines the destination rectangle that the applyFilter() method call affects, given a BitmapData object, a source rectangle, and a filter object.

For example, a blur filter normally affects an area larger than the size of the original image. A 100 x 200 pixel image that is being filtered by a default BlurFilter instance, where blurX = blurY = 4 generates a destination rectangle of (-2,-2,104,204). The generateFilterRect() method lets you find out the size of this destination rectangle in advance so that you can size the destination image appropriately before you perform a filter operation.

Some filters clip their destination rectangle based on the source image size. For example, an inner DropShadow does not generate a larger result than its source image. In this API, the BitmapData object is used as the source bounds and not the source rect parameter.

Parameters
sourceRect:Rectangle — A rectangle defining the area of the source image to use as input.
 
filter:BitmapFilter — A filter object that you use to calculate the destination rectangle.

Returns
Rectangle — A destination rectangle computed by using an image, the sourceRect parameter, and a filter.

Throws
TypeError — The sourceRect or filter are null.

Example
The following example shows how you can use the generateFilterRect() method to determine the rectangular area that the result of a blur filter will occupy. The results of the generateFilterRect() method are output by the trace() function:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.filters.BlurFilter;

var bmd:BitmapData = new BitmapData(80, 30, false, 0xFFCC00);
var rect:Rectangle = new Rectangle(10, 10, 40, 10);
bmd.fillRect(rect, 0xFF0000);

var pt:Point = new Point(10, 10);
var filter:BlurFilter = new BlurFilter();

trace(bmd.generateFilterRect(rect, filter));
// (x=8, y=8, w=44, h=14)

bmd.applyFilter(bmd, rect, pt, filter);
var bm:Bitmap = new Bitmap(bmd);
addChild(bm);
Note that the generateFilterRect() method does not apply the filter. Call the applyFilter() method to apply the filter.

getColorBoundsRect()method 
public function getColorBoundsRect(mask:uint, color:uint, findColor:Boolean = true):Rectangle

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Determines a rectangular region that either fully encloses all pixels of a specified color within the bitmap image (if the findColor parameter is set to true) or fully encloses all pixels that do not include the specified color (if the findColor parameter is set to false).

For example, if you have a source image and you want to determine the rectangle of the image that contains a nonzero alpha channel, pass {mask: 0xFF000000, color: 0x00000000} as parameters. If the findColor parameter is set to true, the entire image is searched for the bounds of pixels for which (value & mask) == color (where value is the color value of the pixel). If the findColor parameter is set to false, the entire image is searched for the bounds of pixels for which (value & mask) != color (where value is the color value of the pixel). To determine white space around an image, pass {mask: 0xFFFFFFFF, color: 0xFFFFFFFF} to find the bounds of nonwhite pixels.

Parameters
mask:uint — A hexadecimal value, specifying the bits of the ARGB color to consider. The color value is combined with this hexadecimal value, by using the & (bitwise AND) operator.
 
color:uint — A hexadecimal value, specifying the ARGB color to match (if findColor is set to true) or not to match (if findColor is set to false).
 
findColor:Boolean (default = true) — If the value is set to true, returns the bounds of a color value in an image. If the value is set to false, returns the bounds of where this color doesn't exist in an image.

Returns
Rectangle — The region of the image that is the specified color.

Example
The following example creates a BitmapData object with red in the top half of its pixels. It then calls the getColorBoundsRect() method to determine the rectangle in which pixels are red (0xFF0000), and then it calls the same method to determine the rectangle in which pixels are not red (by setting the findColor parameter to false:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;

var bmd:BitmapData = new BitmapData(80, 40, false, 0xFFFFFF);
var rect:Rectangle = new Rectangle(0, 0, 80, 20);
bmd.fillRect(rect, 0xFF0000);

var maskColor:uint = 0xFFFFFF; 
var color:uint = 0xFF0000;  
var redBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, true);
trace(redBounds); // (x=0, y=0, w=80, h=20)

var notRedBounds:Rectangle = bmd.getColorBoundsRect(maskColor, color, false);
trace(notRedBounds); // (x=0, y=20, w=80, h=20)

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

getPixel()method 
public function getPixel(x:int, y:int):uint

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Returns an integer that represents an RGB pixel value from a BitmapData object at a specific point (x, y). The getPixel() method returns an unmultiplied pixel value. No alpha information is returned.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

Parameters
x:int — The x position of the pixel.
 
y:int — The y position of the pixel.

Returns
uint — A number that represents an RGB pixel value. If the (x, y) coordinates are outside the bounds of the image, the method returns 0.

See also


Example
The following example creates a BitmapData object filled with red, then uses the getPixel() method to determine the color value in the upper-left pixel:
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(80, 40, false, 0xFF0000);

var pixelValue:uint = bmd.getPixel(0, 0);
trace(pixelValue.toString(16)); // ff0000;

getPixel32()method 
public function getPixel32(x:int, y:int):uint

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Returns an ARGB color value that contains alpha channel data and RGB data. This method is similar to the getPixel() method, which returns an RGB color without alpha channel data.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

Parameters
x:int — The x position of the pixel.
 
y:int — The y position of the pixel.

Returns
uint — A number representing an ARGB pixel value. If the (x, y) coordinates are outside the bounds of the image, 0 is returned.

See also


Example
The following example creates a BitmapData object filled with a color, then uses the getPixel32() method to determine the color value in the upper-left pixel, and then determines the hexidecimal values for each color component (alpha, red, green, and blue):

import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(80, 40, true, 0xFF44AACC);

var pixelValue:uint = bmd.getPixel32(0, 0);
var alphaValue:uint = pixelValue >> 24 & 0xFF;
var red:uint = pixelValue >> 16 & 0xFF;
var green:uint = pixelValue >> 8 & 0xFF;
var blue:uint = pixelValue & 0xFF;

trace(alphaValue.toString(16)); // ff
trace(red.toString(16)); // 44
trace(green.toString(16)); // aa
trace(blue.toString(16)); // cc

getPixels()method 
public function getPixels(rect:Rectangle):ByteArray

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Generates a byte array from a rectangular region of pixel data. Writes an unsigned integer (a 32-bit unmultiplied pixel value) for each pixel into the byte array.

Parameters
rect:Rectangle — A rectangular area in the current BitmapData object.

Returns
ByteArray — A ByteArray representing the pixels in the given Rectangle.

Throws
TypeError — The rect is null.

See also


Example
The following example creates a BitmapData object filled with random noise pixels, then uses the getPixels() method to fill a ByteArray object with the pixel values of the BitmapData object
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

var bmd:BitmapData = new BitmapData(80, 40, true);
var seed:int = int(Math.random() * int.MAX_VALUE);
bmd.noise(seed);

var bounds:Rectangle = new Rectangle(0, 0, bmd.width, bmd.height);
var pixels:ByteArray = bmd.getPixels(bounds);

getVector()method 
public function getVector(rect:Rectangle):Vector.<uint>

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Generates a vector array from a rectangular region of pixel data. Returns a Vector object of unsigned integers (a 32-bit unmultiplied pixel value) for the specified rectangle.

Parameters
rect:Rectangle — A rectangular area in the current BitmapData object.

Returns
Vector.<uint> — A Vector representing the given Rectangle.

Throws
TypeError — The rect is null.
histogram()method 
public function histogram(hRect:Rectangle = null):Vector.<Vector.<Number>>

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Computes a 256-value binary number histogram of a BitmapData object. This method returns a Vector object containing four Vector.<Number> instances (four Vector objects that contain Number objects). The four Vector instances represent the red, green, blue and alpha components in order. Each Vector instance contains 256 values that represent the population count of an individual component value, from 0 to 255.

Parameters
hRect:Rectangle (default = null) — The area of the BitmapData object to use.

Returns
Vector.<Vector.<Number>>
hitTest()method 
public function hitTest(firstPoint:Point, firstAlphaThreshold:uint, secondObject:Object, secondBitmapDataPoint:Point = null, secondAlphaThreshold:uint = 1):Boolean

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Performs pixel-level hit detection between one bitmap image and a point, rectangle, or other bitmap image. A hit is defined as an overlap of a point or rectangle over an opaque pixel, or two overlapping opaque pixels. No stretching, rotation, or other transformation of either object is considered when the hit test is performed.

If an image is an opaque image, it is considered a fully opaque rectangle for this method. Both images must be transparent images to perform pixel-level hit testing that considers transparency. When you are testing two transparent images, the alpha threshold parameters control what alpha channel values, from 0 to 255, are considered opaque.

Parameters
firstPoint:Point — A position of the upper-left corner of the BitmapData image in an arbitrary coordinate space. The same coordinate space is used in defining the secondBitmapPoint parameter.
 
firstAlphaThreshold:uint — The smallest alpha channel value that is considered opaque for this hit test.
 
secondObject:Object — A Rectangle, Point, Bitmap, or BitmapData object.
 
secondBitmapDataPoint:Point (default = null) — A point that defines a pixel location in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object.
 
secondAlphaThreshold:uint (default = 1) — The smallest alpha channel value that is considered opaque in the second BitmapData object. Use this parameter only when the value of secondObject is a BitmapData object and both BitmapData objects are transparent.

Returns
Boolean — A value of true if a hit occurs; otherwise, false.

Throws
ArgumentError — The secondObject parameter is not a Point, Rectangle, Bitmap, or BitmapData object.
 
TypeError — The firstPoint is null.

Example
The following example creates a BitmapData object that is only opaque in a rectangular region (20, 20, 40, 40) and calls the hitTest() method with a Point object as the secondObject. In the first call, the Point object defines the upper-left corner of the BitmapData object, which is not opaque, and in the second call, the Point object defines the center of the BitmapData object, which is opaque.
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

var bmd1:BitmapData = new BitmapData(80, 80, true, 0x00000000);
var rect:Rectangle = new Rectangle(20, 20, 40, 40);
bmd1.fillRect(rect, 0xFF0000FF);

var pt1:Point = new Point(1, 1);
trace(bmd1.hitTest(pt1, 0xFF, pt1)); // false
var pt2:Point = new Point(40, 40);
trace(bmd1.hitTest(pt1, 0xFF, pt2)); // true

lock()method 
public function lock():void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Locks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are not updated when this BitmapData object changes. To improve performance, use this method along with the unlock() method before and after numerous calls to the setPixel() or setPixel32() method.

See also


Example
The following example creates a BitmapData object based on the bitmapData property of a Bitmap object, picture. It then calls the lock() method before calling a complicated custom function, complexTransformation(), that modifies the BitmapData object. (The picture object and the complexTransformation() function are not defined in this example.) Even if the complexTransformation() function updates the bitmapData property of the picture object, changes are not reflected until the code calls the unlock() method on the bitmapData object:
import flash.display.BitmapData;

var bitmapData:BitmapData = picture.bitmapData;
bitmapData.lock();
bitmapData = complexTransformation(bitmapData);
bitmapData.unlock();
picture.bitmapData = bitmapData;

merge()method 
public function merge(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redMultiplier:uint, greenMultiplier:uint, blueMultiplier:uint, alphaMultiplier:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Performs per-channel blending from a source image to a destination image. For each channel and each pixel, a new value is computed based on the channel values of the source and destination pixels. For example, in the red channel, the new value is computed as follows (where redSrc is the red channel value for a pixel in the source image and redDest is the red channel value at the corresponding pixel of the destination image):

new redDest = [(redSrc * redMultiplier) + (redDest * (256 - redMultiplier))] / 256;

The redMultiplier, greenMultiplier, blueMultiplier, and alphaMultiplier values are the multipliers used for each color channel. Use a hexadecimal value ranging from 0 to 0x100 (256) where 0 specifies the full value from the destination is used in the result, 0x100 specifies the full value from the source is used, and numbers in between specify a blend is used (such as 0x80 for 50%).

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData object.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle.
 
redMultiplier:uint — A hexadecimal uint value by which to multiply the red channel value.
 
greenMultiplier:uint — A hexadecimal uint value by which to multiply the green channel value.
 
blueMultiplier:uint — A hexadecimal uint value by which to multiply the blue channel value.
 
alphaMultiplier:uint — A hexadecimal uint value by which to multiply the alpha transparency value.

Throws
TypeError — The sourceBitmapData, sourceRect or destPoint are null.

Example
The following example creates two BitmapData objects. Both are 100 x 80 pixels in size. The first is filled with green and the second is filled with red. The code calls the merge() method, merging the second BitmapData pixels into the first BitmapData object, but only on a specified rectangular area:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

var bmd1:BitmapData = new BitmapData(100, 80, true, 0xFF00FF00);
var bmd2:BitmapData = new BitmapData(100, 80, true, 0xFFFF0000);
var rect:Rectangle = new Rectangle(0, 0, 20, 20);
var pt:Point = new Point(20, 20);
var mult:uint = 0x80; // 50% 
bmd1.merge(bmd2, rect, pt, mult, mult, mult, mult);

var bm1:Bitmap = new Bitmap(bmd1);
addChild(bm1);
var bm2:Bitmap = new Bitmap(bmd2);
addChild(bm2);
bm2.x = 110;

noise()method 
public function noise(randomSeed:int, low:uint = 0, high:uint = 255, channelOptions:uint = 7, grayScale:Boolean = false):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Fills an image with pixels representing random noise.

Parameters
randomSeed:int — The random seed number to use. If you keep all other parameters the same, you can generate different pseudo-random results by varying the random seed value. The noise function is a mapping function, not a true random-number generation function, so it creates the same results each time from the same random seed.
 
low:uint (default = 0) — The lowest value to generate for each channel (0 to 255).
 
high:uint (default = 255) — The highest value to generate for each channel (0 to 255).
 
channelOptions:uint (default = 7) — A number that can be a combination of any of the four color channel values (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and BitmapDataChannel.ALPHA). You can use the logical OR operator (|) to combine channel values.
 
grayScale:Boolean (default = false) — A Boolean value. If the value is true, a grayscale image is created by setting all of the color channels to the same value. The alpha channel selection is not affected by setting this parameter to true.

See also


Example
The following example creates two BitmapData objects and calls the noise() method on both. However, the grayscale parameter is set to false for the call to the noise() method of the first object, and it is set to true for the call to the noise() method of the second object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;

var bmd1:BitmapData = new BitmapData(80, 80);
var bmd2:BitmapData = new BitmapData(80, 80);

var seed:int = int(Math.random() * int.MAX_VALUE);
bmd1.noise(seed, 0, 0xFF, BitmapDataChannel.RED, false);
bmd2.noise(seed, 0, 0xFF, BitmapDataChannel.RED, true);

var bm1:Bitmap = new Bitmap(bmd1);
this.addChild(bm1);
var bm2:Bitmap = new Bitmap(bmd2);
this.addChild(bm2);
bm2.x = 90;

paletteMap()method 
public function paletteMap(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, redArray:Array = null, greenArray:Array = null, blueArray:Array = null, alphaArray:Array = null):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Remaps the color channel values in an image that has up to four arrays of color palette data, one for each channel.

Flash runtimes use the following steps to generate the resulting image:

  1. After the red, green, blue, and alpha values are computed, they are added together using standard 32-bit-integer arithmetic.
  2. The red, green, blue, and alpha channel values of each pixel are extracted into separate 0 to 255 values. These values are used to look up new color values in the appropriate array: redArray, greenArray, blueArray, and alphaArray. Each of these four arrays should contain 256 values.
  3. After all four of the new channel values are retrieved, they are combined into a standard ARGB value that is applied to the pixel.

Cross-channel effects can be supported with this method. Each input array can contain full 32-bit values, and no shifting occurs when the values are added together. This routine does not support per-channel clamping.

If no array is specified for a channel, the color channel is copied from the source image to the destination image.

You can use this method for a variety of effects such as general palette mapping (taking one channel and converting it to a false color image). You can also use this method for a variety of advanced color manipulation algorithms, such as gamma, curves, levels, and quantizing.

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData instance.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The point within the destination image (the current BitmapData object) that corresponds to the upper-left corner of the source rectangle.
 
redArray:Array (default = null) — If redArray is not null, red = redArray[source red value] else red = source rect value.
 
greenArray:Array (default = null) — If greenArray is not null, green = greenArray[source green value] else green = source green value.
 
blueArray:Array (default = null) — If blueArray is not null, blue = blueArray[source blue value] else blue = source blue value.
 
alphaArray:Array (default = null) — If alphaArray is not null, alpha = alphaArray[source alpha value] else alpha = source alpha value.

Throws
TypeError — The sourceBitmapData, sourceRect or destPoint are null.

Example
The following example creates a green BitmapData object with a red center square, and then uses the paletteMap() method to swap red with green in the bottom rectangular half of the BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;
import flash.geom.Point;

var myBitmapData:BitmapData = new BitmapData(80, 80, false, 0x00FF0000);
myBitmapData.fillRect(new Rectangle(20, 20, 40, 40), 0x0000FF00);

var redArray:Array = new Array(256);
var greenArray:Array = new Array(256);

for(var i:uint = 0; i < 255; i++) {
    redArray[i] = 0x00000000;
	greenArray[i] = 0x00000000;
}

redArray[0xFF] = 0x0000FF00;
greenArray[0xFF] = 0x00FF0000;

var bottomHalf:Rectangle = new Rectangle(0, 0, 100, 40);
var pt:Point = new Point(0, 0);
myBitmapData.paletteMap(myBitmapData, bottomHalf, pt, redArray, greenArray);

var bm1:Bitmap = new Bitmap(myBitmapData);
addChild(bm1);

perlinNoise()method 
public function perlinNoise(baseX:Number, baseY:Number, numOctaves:uint, randomSeed:int, stitch:Boolean, fractalNoise:Boolean, channelOptions:uint = 7, grayScale:Boolean = false, offsets:Array = null):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Generates a Perlin noise image.

The Perlin noise generation algorithm interpolates and combines individual random noise functions (called octaves) into a single function that generates more natural-seeming random noise. Like musical octaves, each octave function is twice the frequency of the one before it. Perlin noise has been described as a "fractal sum of noise" because it combines multiple sets of noise data with different levels of detail.

You can use Perlin noise functions to simulate natural phenomena and landscapes, such as wood grain, clouds, and mountain ranges. In most cases, the output of a Perlin noise function is not displayed directly but is used to enhance other images and give them pseudo-random variations.

Simple digital random noise functions often produce images with harsh, contrasting points. This kind of harsh contrast is not often found in nature. The Perlin noise algorithm blends multiple noise functions that operate at different levels of detail. This algorithm results in smaller variations among neighboring pixel values.

Parameters
baseX:Number — Frequency to use in the x direction. For example, to generate a noise that is sized for a 64 x 128 image, pass 64 for the baseX value.
 
baseY:Number — Frequency to use in the y direction. For example, to generate a noise that is sized for a 64 x 128 image, pass 128 for the baseY value.
 
numOctaves:uint — Number of octaves or individual noise functions to combine to create this noise. Larger numbers of octaves create images with greater detail. Larger numbers of octaves also require more processing time.
 
randomSeed:int — The random seed number to use. If you keep all other parameters the same, you can generate different pseudo-random results by varying the random seed value. The Perlin noise function is a mapping function, not a true random-number generation function, so it creates the same results each time from the same random seed.
 
stitch:Boolean — A Boolean value. If the value is true, the method attempts to smooth the transition edges of the image to create seamless textures for tiling as a bitmap fill.
 
fractalNoise:Boolean — A Boolean value. If the value is true, the method generates fractal noise; otherwise, it generates turbulence. An image with turbulence has visible discontinuities in the gradient that can make it better approximate sharper visual effects like flames and ocean waves.
 
channelOptions:uint (default = 7) — A number that can be a combination of any of the four color channel values (BitmapDataChannel.RED, BitmapDataChannel.BLUE, BitmapDataChannel.GREEN, and BitmapDataChannel.ALPHA). You can use the logical OR operator (|) to combine channel values.
 
grayScale:Boolean (default = false) — A Boolean value. If the value is true, a grayscale image is created by setting each of the red, green, and blue color channels to identical values. The alpha channel value is not affected if this value is set to true.
 
offsets:Array (default = null) — An array of points that correspond to x and y offsets for each octave. By manipulating the offset values you can smoothly scroll the layers of a perlinNoise image. Each point in the offset array affects a specific octave noise function.

Example
The following example creates a 200 x 200 pixel BitmapData object that calls the perlinNoise() method to generate a red and blue watercolor effect:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(200, 200, false, 0x00CCCCCC);

var seed:Number = Math.floor(Math.random() * 10);
var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE;
bmd.perlinNoise(100, 80, 6, seed, false, true, channels, false, null);

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

pixelDissolve()method 
public function pixelDissolve(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, randomSeed:int = 0, numPixels:int = 0, fillColor:uint = 0):int

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Performs a pixel dissolve either from a source image to a destination image or by using the same image. Flash runtimes use a randomSeed value to generate a random pixel dissolve. The return value of the function must be passed in on subsequent calls to continue the pixel dissolve until it is finished.

If the source image does not equal the destination image, pixels are copied from the source to the destination by using all of the properties. This process allows dissolving from a blank image into a fully populated image.

If the source and destination images are equal, pixels are filled with the color parameter. This process allows dissolving away from a fully populated image. In this mode, the destination point parameter is ignored.

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object, or it can refer to the current BitmapData instance.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle.
 
randomSeed:int (default = 0) — The random seed to use to start the pixel dissolve.
 
numPixels:int (default = 0) — The default is 1/30 of the source area (width x height).
 
fillColor:uint (default = 0) — An ARGB color value that you use to fill pixels whose source value equals its destination value.

Returns
int — The new random seed value to use for subsequent calls.

Throws
TypeError — The sourceBitmapData, sourceRect or destPoint are null.
 
TypeError — The numPixels value is negative

Example
The following example uses the pixelDissolve() method to convert a grey BitmapData object to a red one by dissolving 40 pixels at a time until all pixels have changed colors:
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.utils.Timer;
import flash.events.TimerEvent;

var bmd:BitmapData = new BitmapData(100, 80, false, 0x00CCCCCC);
var bitmap:Bitmap = new Bitmap(bmd);
addChild(bitmap);

var tim:Timer = new Timer(20);
tim.start();
tim.addEventListener(TimerEvent.TIMER, timerHandler);
 
function timerHandler(event:TimerEvent):void {
    var randomNum:Number = Math.floor(Math.random() * int.MAX_VALUE);
    dissolve(randomNum);
}

function dissolve(randomNum:Number):void {
    var rect:Rectangle = bmd.rect;
	var pt:Point = new Point(0, 0);
	var numberOfPixels:uint = 100;
	var red:uint = 0x00FF0000;
	bmd.pixelDissolve(bmd, rect, pt, randomNum, numberOfPixels, red);
	var grayRegion:Rectangle = bmd.getColorBoundsRect(0xFFFFFFFF, 0x00CCCCCC, true);
	if(grayRegion.width == 0 && grayRegion.height == 0 ) {
		tim.stop();
	}
}

scroll()method 
public function scroll(x:int, y:int):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Scrolls an image by a certain (x, y) pixel amount. Edge regions outside the scrolling area are left unchanged.

Parameters
x:int — The amount by which to scroll horizontally.
 
y:int — The amount by which to scroll vertically.

Example
The following example shows the effect of scrolling a Bitmap data object 40 pixels to the right:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Rectangle;

var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC);
var rect:Rectangle = new Rectangle(0, 0, 40, 40);
bmd.fillRect(rect, 0xFFFF0000);
    		
var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

trace (bmd.getPixel32(50, 20).toString(16)); // ffcccccccc

bmd.scroll(30, 0); 

trace (bmd.getPixel32(50, 20).toString(16)); // ffff0000

setPixel()method 
public function setPixel(x:int, y:int, color:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Sets a single pixel of a BitmapData object. The current alpha channel value of the image pixel is preserved during this operation. The value of the RGB color parameter is treated as an unmultiplied color value.

Note: To increase performance, when you use the setPixel() or setPixel32() method repeatedly, call the lock() method before you call the setPixel() or setPixel32() method, and then call the unlock() method when you have made all pixel changes. This process prevents objects that reference this BitmapData instance from updating until you finish making the pixel changes.

Parameters
x:int — The x position of the pixel whose value changes.
 
y:int — The y position of the pixel whose value changes.
 
color:uint — The resulting RGB color for the pixel.

See also


Example
The following example uses the setPixel() method to draw a red line in a BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(80, 80, false, 0xCCCCCC);

for (var i:uint = 0; i < 80; i++) {
    var red:uint = 0xFF0000;
	bmd.setPixel(i, 40, red);
}

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

setPixel32()method 
public function setPixel32(x:int, y:int, color:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Sets the color and alpha transparency values of a single pixel of a BitmapData object. This method is similar to the setPixel() method; the main difference is that the setPixel32() method takes an ARGB color value that contains alpha channel information.

All pixels in a BitmapData object are stored as premultiplied color values. A premultiplied image pixel has the red, green, and blue color channel values already multiplied by the alpha data. For example, if the alpha value is 0, the values for the RGB channels are also 0, independent of their unmultiplied values. This loss of data can cause some problems when you perform operations. All BitmapData methods take and return unmultiplied values. The internal pixel representation is converted from premultiplied to unmultiplied before it is returned as a value. During a set operation, the pixel value is premultiplied before the raw image pixel is set.

Note: To increase performance, when you use the setPixel() or setPixel32() method repeatedly, call the lock() method before you call the setPixel() or setPixel32() method, and then call the unlock() method when you have made all pixel changes. This process prevents objects that reference this BitmapData instance from updating until you finish making the pixel changes.

Parameters
x:int — The x position of the pixel whose value changes.
 
y:int — The y position of the pixel whose value changes.
 
color:uint — The resulting ARGB color for the pixel. If the bitmap is opaque (not transparent), the alpha transparency portion of this color value is ignored.

See also


Example
The following example uses the setPixel32() method to draw a transparent (alpha == 0x60) red line in a BitmapData object:

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(80, 80, true, 0xFFCCCCCC);

for (var i:uint = 0; i < 80; i++) {
    var red:uint = 0x60FF0000;
	bmd.setPixel32(i, 40, red);
}

var bm:Bitmap = new Bitmap(bmd);
addChild(bm);

setPixels()method 
public function setPixels(rect:Rectangle, inputByteArray:ByteArray):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Converts a byte array into a rectangular region of pixel data. For each pixel, the ByteArray.readUnsignedInt() method is called and the return value is written into the pixel. If the byte array ends before the full rectangle is written, the function returns. The data in the byte array is expected to be 32-bit ARGB pixel values. No seeking is performed on the byte array before or after the pixels are read.

Parameters
rect:Rectangle — Specifies the rectangular region of the BitmapData object.
 
inputByteArray:ByteArray — A ByteArray object that consists of 32-bit unmultiplied pixel values to be used in the rectangular region.

Throws
Error — The inputByteArray object does not include enough data to fill the area of the rect rectangle. The method fills as many pixels as possible before throwing the exception.
 
TypeError — The rect or inputByteArray are null.

See also


Example
The following example uses the getPixels() and setPixels() methods to copy pixels from one BitmapData object to another:

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
import flash.geom.Rectangle;

var bmd1:BitmapData = new BitmapData(100, 100, true, 0xFFCCCCCC);
var bmd2:BitmapData = new BitmapData(100, 100, true, 0xFFFF0000);

var rect:Rectangle = new Rectangle(0, 0, 100, 100);
var bytes:ByteArray = bmd1.getPixels(rect);

bytes.position = 0;
bmd2.setPixels(rect, bytes);

var bm1:Bitmap = new Bitmap(bmd1);
addChild(bm1);
var bm2:Bitmap = new Bitmap(bmd2);
addChild(bm2);
bm2.x = 110;

setVector()method 
public function setVector(rect:Rectangle, inputVector:Vector.<uint>):void

Language version: ActionScript 3.0
Runtime version: AIR 1.5

Converts a Vector into a rectangular region of pixel data. For each pixel, a Vector element is read and written into the BitmapData pixel. The data in the Vector is expected to be 32-bit ARGB pixel values.

Parameters
rect:Rectangle — Specifies the rectangular region of the BitmapData object.
 
inputVector:Vector.<uint> — A Vector object that consists of 32-bit unmultiplied pixel values to be used in the rectangular region.

Throws
RangeError — The vector array is not large enough to read all the pixel data.
threshold()method 
public function threshold(sourceBitmapData:BitmapData, sourceRect:Rectangle, destPoint:Point, operation:String, threshold:uint, color:uint = 0, mask:uint = 0xFFFFFFFF, copySource:Boolean = false):uint

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Tests pixel values in an image against a specified threshold and sets pixels that pass the test to new color values. Using the threshold() method, you can isolate and replace color ranges in an image and perform other logical operations on image pixels.

The threshold() method's test logic is as follows:

  1. If ((pixelValue & mask) operation (threshold & mask)), then set the pixel to color;
  2. Otherwise, if copySource == true, then set the pixel to corresponding pixel value from sourceBitmap.

The operation parameter specifies the comparison operator to use for the threshold test. For example, by using "==" as the operation parameter, you can isolate a specific color value in an image. Or by using {operation: "<", mask: 0xFF000000, threshold: 0x7F000000, color: 0x00000000}, you can set all destination pixels to be fully transparent when the source image pixel's alpha is less than 0x7F. You can use this technique for animated transitions and other effects.

Parameters
sourceBitmapData:BitmapData — The input bitmap image to use. The source image can be a different BitmapData object or it can refer to the current BitmapData instance.
 
sourceRect:Rectangle — A rectangle that defines the area of the source image to use as input.
 
destPoint:Point — The point within the destination image (the current BitmapData instance) that corresponds to the upper-left corner of the source rectangle.
 
operation:String — One of the following comparison operators, passed as a String: "<", "<=", ">", ">=", "==", "!="
 
threshold:uint — The value that each pixel is tested against to see if it meets or exceeds the threshhold.
 
color:uint (default = 0) — The color value that a pixel is set to if the threshold test succeeds. The default value is 0x00000000.
 
mask:uint (default = 0xFFFFFFFF) — The mask to use to isolate a color component.
 
copySource:Boolean (default = false) — If the value is true, pixel values from the source image are copied to the destination when the threshold test fails. If the value is false, the source image is not copied when the threshold test fails.

Returns
uint — The number of pixels that were changed.

Throws
TypeError — The sourceBitmapData, sourceRect destPoint or operation are null.
 
ArgumentError — The operation string is not a valid operation

Example
The following example uses the perlinNoise() method to add a blue and red pattern to one BitmapData object, and then uses the threshold() method to copy those pixels from the first BitmapData object to a second one, replacing those pixels in which the red value is greater than 0x80 (50%) with a pixel set to transparent red (0x20FF0000):

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.geom.Point;
import flash.geom.Rectangle;

var bmd1:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC);

var seed:int = int(Math.random() * int.MAX_VALUE);
var channels:uint = BitmapDataChannel.RED | BitmapDataChannel.BLUE;
bmd1.perlinNoise(100, 80, 12, seed, false, true, channels, false, null);

var bitmap1:Bitmap = new Bitmap(bmd1);
addChild(bitmap1);

var bmd2:BitmapData = new BitmapData(200, 200, true, 0xFFCCCCCC);
var pt:Point = new Point(0, 0);
var rect:Rectangle = new Rectangle(0, 0, 200, 200);
var threshold:uint =  0x00800000; 
var color:uint = 0x20FF0000;
var maskColor:uint = 0x00FF0000;
bmd2.threshold(bmd1, rect, pt, ">", threshold, color, maskColor, true);

var bitmap2:Bitmap = new Bitmap(bmd2);
bitmap2.x = bitmap1.x + bitmap1.width + 10;
addChild(bitmap2);

unlock()method 
public function unlock(changeRect:Rectangle = null):void

Language version: ActionScript 3.0
Runtime version: AIR 1.0

Unlocks an image so that any objects that reference the BitmapData object, such as Bitmap objects, are updated when this BitmapData object changes. To improve performance, use this method along with the lock() method before and after numerous calls to the setPixel() or setPixel32() method.

Parameters
changeRect:Rectangle (default = null) — The area of the BitmapData object that has changed. If you do not specify a value for this parameter, the entire area of the BitmapData object is considered changed. This parameter requires Flash Player version 9.0.115.0 or later.

See also


Example
The following example creates a BitmapData object based on the bitmapData property of a Bitmap object, picture. It then calls the lock() method before calling a complicated custom function, complexTransformation(), that modifies the BitmapData object. (The picture object and the complexTransformation() function are not defined in this example.) Even if the complexTransformation() function updates the bitmapData property of the picture object, changes are not reflected until the code calls the unlock() method on the bitmapData object:
import flash.display.BitmapData;

var bitmapData:BitmapData = picture.bitmapData;
bitmapData.lock();
bitmapData = complexTransformation(bitmapData);
bitmapData.unlock();
picture.bitmapData = bitmapData;

Examples
examples\BitmapDataExample
The following example uses the class BitmapDataExample to load the image Image.gif into a DisplayObject in the default location (0, 0). A copy of Image.gif is then placed to the right of the original, which has new colors applied to pixels that pass a test using the threshold() method. The task is accomplished using the following steps:
  1. A url property is created, which is the location and name of the image file
  2. The class constructor creates a Loader object, which then instantiates an event listener, which is dispatched when the completeHandler() method completes the image manipulation.
  3. The request URLRequest object is then passed to loader.load(), which loads the image into memory by using a display object.
  4. The image is then placed on the display list, which displays the image on screen at coordinates x = 0, y = 0.
  5. The completeHandler() method then does the following:
    • Creates a second Loader, along with a Bitmap object, which is initialized with the Loader object.
    • Creates a second Bitmap object, duplicate, which in turn calls the duplicateImage() method, which creates a duplicate of the original image.
    • Creates a BitmapData object that is assigned to the duplicate object's BitmapData object.
    • Creates a new Rectangle object initialized with the same coordinates, width, and height as the original image.
    • Creates a new Point object, which defaults to x = 0, y = 0.
    • Creates the following variables:
      • operation — Applies the new color when the threshold value is greater than or equal to the original.
      • threshold — The value against which each pixel is compared (in this example, light gray with an alpha of 0xCC).
      • color — The color that the pixels are set to that pass the threshold test, which is solid yellow in this case.
      • mask — The exact opposite of color (transparent blue).
      • copySource — Set to false, indicating the pixel values are not copied if the threshold value does not pass. This value has no meaning because the image is duplicated and only pixels that pass the threshold test are changed.
    • Calls the threshold() method using the preceding variables. The resulting threshold equation is as follows: if (current pixel Value & 0x000000FF) >= (0xCCCCCCCC & 0x000000FF) then set pixel to 0xFFFFFF00.

Notes:


package {
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.*;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    import flash.net.URLRequest;

    public class BitmapDataExample extends Sprite {
        private var url:String = "Image.gif";
        private var size:uint = 80;

        public function BitmapDataExample() {
            configureAssets();
        }

        private function configureAssets():void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
            loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

            var request:URLRequest = new URLRequest(url);
            loader.x = size * numChildren;
            loader.load(request);
            addChild(loader);
        }

        private function duplicateImage(original:Bitmap):Bitmap {
            var image:Bitmap = new Bitmap(original.bitmapData.clone());
            image.x = size * numChildren;
            addChild(image);
            return image;
        }

        private function completeHandler(event:Event):void {
            var loader:Loader = Loader(event.target.loader);
            var image:Bitmap = Bitmap(loader.content);

            var duplicate:Bitmap = duplicateImage(image);
            var bitmapData:BitmapData = duplicate.bitmapData;
            var sourceRect:Rectangle = new Rectangle(0, 0, bitmapData.width, bitmapData.height);
            var destPoint:Point = new Point();
            var operation:String = ">=";
            var threshold:uint = 0xCCCCCCCC;
            var color:uint = 0xFFFFFF00;
            var mask:uint = 0x000000FF;
            var copySource:Boolean = true;

            bitmapData.threshold(bitmapData,
                                 sourceRect,
                                 destPoint,
                                 operation,
                                 threshold,
                                 color,
                                 mask,
                                 copySource);
        }
        
        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("Unable to load image: " + url);
        }
    }
}
examples\BitmapDataExample2