PNGEncoder2 is a library to compresses BitmapData objects into PNG files stored in ByteArray objects. The code was originally written in the Haxe language, but it is possible to compile it to a SWC file and use it with any AS3 project. The library is highly tuned for speed, outperforming the as3corelib PNGEncoder by up to 5x (on the FAST setting). This is made possible by the custom DEFLATE library written from scratch specifically for this encoder. The custom DEFLATE implementation also allows a developer to choose between compression levels: FAST, NORMAL, GOOD and UNCOMPRESSED.

The library has a true asynchronous encoding that is different from most of the other asynchronous PNG encoders. They usually do the conversion from bitmap data to PNG data asynchronously, then call ByteArray.compress() at the end, which is a long, synchronous operation that can take half the total encoding time or more. As a result, the library has a completely smooth encoding, asynchronously (with progress events) and scales to a target FPS without wasting any cycles idling.

It can also compress large images on-the-fly, since it does the work in manageable chunks (when done asynchronously) instead of all at once. There is no single-step bottleneck. If the BitmapData is not transparent, then it will be automatically encoded using the (generally smaller) 24-bit PNG format, otherwise the 32-bit format is used.


var bmp : BitmapData = ...;     // The bitmap you want to encode

PNGEncoder2.level = CompressionLevel.FAST;  // Optional. Defaults to FAST

var encoder : PNGEncoder2 = PNGEncoder2.encodeAsync(bmp);
encoder.targetFPS = 12;     // Optional. Defaults to 20. Lower FPSs yield faster compression

// Because the encoder is guaranteed to fire the COMPLETE event
// after at least one frame, it's safe to attach the listener after
// starting the encoding (as long as it's done before the next frame)
encoder.addEventListener(Event.COMPLETE, function (e) {
    var png : ByteArray = encoder.png;

    var bmp2 : BitmapData = ...;
    bmp2 = PNGEncoder2.decode(png);    // Decode the data back to a Bitmap

// encoder also dispatches ProgressEvent.PROGRESS events if you
// want to be notified of progress
Misc . URL.