When recently playing with Alchemy for AlivePDF I looked at the libjpeg library and thought it would be cool to expose the JPEG decoding capability to ActionScript 3 developers. As some of you may know, the libjpeg can also be used to encode JPEG files in a very optimized way.
So you may wonder, why the hell would I need a JPEG decoder in AS3 ? The Flash Player does it natively and supports it, its not like decoding animated GIFs, or BMP, etc. Well, for my part, I needed a JPEG decoding class for AlivePDF in order to make the addImageStream method work, which basically embed any JPEG file (any dpi) into any page of the PDF created.
When embedding such a file, you need to provide to the PDF reader some informations, like the image dimensions (width, height), its color space, etc in a synchronous way (Loader.loadBytes() is asynchronous). Hopefully the reader takes care of the pixels decoding, you just tell the reader to decode the pixels using the DCTDecode (Descrete Cosine Transform) algorithm and voilà.
But now, let's say you create an application which needs to fully decode a JPEG file, retrieve the image dimensions just by parsing the jpeg stream, do any processing on the pixels before sending them to a BitmapData or maybe just simply map them to a corresponding BitmapData object, then this library is for you. This could be done without Alchemy and libjpeg but I guess it would be much slower for big images and I was in an Alchemy mood
So here is what the API looks like :
import org.bytearray.jpeg.decoder.JPEGDecoder; var myDecoder:JPEGDecoder = new JPEGDecoder(); myDecoder.parse(jpegStream); var width:uint = myDecoder.width; var height:uint = myDecoder.height; var colorComponents:uint = myDecoder.colorComponents; var numComponents:uint = myDecoder.numComponents; var pixels:Vector.<uint> = myDecoder.pixels;
The pixels getter returns an ARGB Vector that you can pass to the fast BitmapData.setVector() method.
var width:uint = myDecoder.width; var height:uint = myDecoder.height; var pixels:Vector.<uint> = myDecoder.pixels; var bitmap:BitmapData = new BitmapData ( width, height, false ); bitmap.setVector ( bitmap.rect, pixels );
I will post another version in the following days with more options. Click in the area below to browse for any JPEG file, the pixels are extracted and decompressed in AS3 and sent to a BitmapData object.
Download the sources here.