Tuesday, 7 February 2012

JPEG data with alpha

The GIF and PNG graphics formats have alpha channels but JPEG does not. There may be times though when it's useful to load JPEG data with an alpha channel. Here's how.

var source:BitmapDatanew myJPEG(00);

var data:BitmapData = new BitmapData(source.width, source.height, true, 0);
data.copyChannel(data, data.rectnew Point(00), 
BitmapDataChannel.RED, BitmapDataChannel.ALPHA);
new Colourise(Col.cWhite, Col.cWhite));

The source JPEG data which is a black and white image, with the white area being the area that's to be kept, the black area the area to be made transparent. This is loaded into a BitmapData, but Flash does not create an alpha channel for this, so the first thing to do is to create an identical image with an alpha channel, by creating an empty one the same size and drawing the source into it.

The main work is done by copyChannel, which uses one of the colour channels (red in this case) to overwrite the alpha channel. Finally the whole image is made white, using the Colourise class to keep the code compact.

This works if the whole image is a single colour with alpha: like a stencil or a mask for example. I find I use a lot of images like this which I then colourise and composite at runtime. But if alpha data is needed alongside colour data it's a little more involved.

Two images are used, with the alpha data loaded as above from one. The colour data is in a separate image. To combine them the BitmapData's copyPixels function is used. This has a parameter alphaBitmapData which takes a BitmapData, from which the alpha channel is taken for the result.

No comments:

Post a comment