New Video Tutorial on ByteArray Image Decoding
| I just finished uploading a new tutorial that shows you how to use the ByteArray class to parse and display images in formats that Flash doesn’t natively support, in this case BMP. In the tutorial I explain how to read a file specification and translate that into ActionScript 3.0 code. If you need an introduction to the ByteArray class you can check out my slides from the recent workshop I did in Amsterdam. |
Lee
Using BitmapData.setVector for better performance
During the ByteArray workshop yesterday we wrote some code that parsed a PSD file and displayed it in the Flash Player. As part of this I showed setting the pixels of the BitmapData object using the setPixels method. I had heard that this method was slow but Thibault confirmed this for me. He suggested that I try a new method that was introduced in Flash Player 10 called setVector. This allows you to take a Vector object containing 32-bit floating point numbers and use it to set the pixels in the bitmap. Below is the original code using setPixel which required a nested for loop.
1 2 3 4 5 6 7 8 | var bmd:BitmapData = new BitmapData(width, height); for(var y:int=0; y<height; ++y) { for(var x:int=0; x<width; ++x) { bmd.setPixel(x, y, r.readUnsignedByte()<<16 | g.readUnsignedByte()<<8 | b.readUnsignedByte()); } } |
The new code which takes advantage of setVector is shown below. There is one trick to getting this to work. You have to shift a value of 255 (aka 0xFF) to the far left byte as you need to provide an ARGB number for it to work. Otherwise your pixel would have an alpha of zero.
1 2 3 4 5 6 7 8 9 10 | var numPixels:int = width*height; var pixels:Vector.<uint> = new Vector.<uint>(numPixels, true); for(i=0; i<numPixels; ++i) { pixels[i] = 0xFF<<24 | r.readUnsignedByte()<<16 | g.readUnsignedByte()<<8 | b.readUnsignedByte(); } var bmd:BitmapData = new BitmapData(width, height); bmd.setVector(new Rectangle(0, 0, width, height), pixels); |
The BitmapData class is smart enough to put all the values into the right places in the bitmap so you don’t have to deal with nested loops.
Lee







