I found the Flex 2 docs didn’t really contain an example of using the pixel data getPixels() puts into a ByteArray. I wanted to take the pixels in that ByteArray and have them explode or move around in a controlled fashion not obtainable with a simple Convolution Matrix or DisplacementMap.

I’m not going to go through all of that, but just a quick example of getting data back out of a ByteArray and displaying it again as a copy. Normally copyPixels() would be the better option for this specific task, but this as I say gives the opportunity to move the pixels around indepentently in 3D for example.

If you have the Flash 9 preview, you can simple create a movieclip on stage, named mc and put the following code on frame 1:

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

var imageWidth:uint = mc.width;
var imageHeight:uint = mc.height;

var srcBmp:BitmapData = new BitmapData( imageWidth, imageHeight );
srcBmp.draw( mc );

var pixels:ByteArray = srcBmp.getPixels( new Rectangle(0,0,imageWidth,imageHeight) );
var copyBmp:BitmapData = new BitmapData( imageWidth, imageHeight, true );

pixels.position = 0;

for( var i:uint=0; i<imageHeight ; i++ )
{
  for( var j:uint=0; j<imageWidth; j++ )
  {
    copyBmp.setPixel( j, i, pixels.readUnsignedInt() );
  }
}

var bmp:Bitmap = new Bitmap( copyBmp );
bmp.x = 100;
addChild( bmp );

Probably the only thing that needs pointing out at all is that you can read out a pixel at a time using ByteArray.readUnsignedInt(), this automatically increments the ByteArray’s .position by the required number of bytes. The reason for this is that BitmapData.getPixels() returns a ByteArray of unsigned ints of course (range 0 to 4,294,967,295 – 32bits of data, which allows for the 24-bits of colour, and 8 bits of alpha).