Manipulating Bitmap Images with ActionScript 3

Tue, 08 Sep 2009

I’ve been recently working on a project which involved the manipulation of bitmap data at runtime. The swf would be communicating with a content management system, which only provided coloured images. But since the images needed to be displayed in greyscale as well as in colour, the swf had to do the trick.

In ActionScript you need to use the ColorMatrixFilter to manipulate these properties. A procedure which can be mind boggling and definitely is error-prone.

After a little searching I found the extremely handy class ColorMatrix.as written by ActionScript grandmaster Grant Skinner. You’ll find some examples on his blog and the class itself hosted on google code.

The usage is fairly simple, though you need to take care of the order of the function calls:

import com.gskinner.geom.ColorMatrix;import flash.filters.ColorMatrixFilter;import flash.display.Sprite;/* ... some other code in between ...*/var c:ColorMatrix = new ColorMatrix();c.adjustBrightness(100);c.adjustSaturation(-100);c.adjustContrast(-50);var cmf:ColorMatrixFilter = new ColorMatrixFilter();cmf.matrix = cm;// The following bitmapData is the BitmapData-Object/  derived from an imagefile,// which is loaded at runtime:var bmp:Bitmap =  new Bitmap(bitmapData) ;var s:Sprite = new Sprite();s.addChild( bmp );s.filters=[cmf];// that's it.

It’s a breeze and works like a charm. Just keep in mind, that these lines:

c.adjustBrightness(100);c.adjustSaturation(-100);c.adjustContrast(-50);

will result in a different image compared to the product of these lines:

c.adjustSaturation(-100);c.adjustContrast(-50);c.adjustBrightness(100);