Sunday, 6 March 2011

Flex / AS3: The best way to encode JPEG

Recently in my diploma I need to encode jpeg file on client, after some research I found library created using Alchemy project( from C/C++ language).It allows you to encode jpeg both synchronous and asynchronous with maximum speed(unlike standard encode() method).

After downloading library and including it in your project, you should do:

1. Init library
This nethod should start with application running s:application applicationcomplete="initAlchemy()"

private var init1:CLibInit;
      private var lib : Object; 
      private function initAlchemy():void
        init1 = new CLibInit();
        lib = init1.init();
2.Prepare your image
private var bd:BitmapData ; //your image here
  public var byteArr:ByteArray = bd.getPixels( bd.rect );
3.1 Encode your image synchronous
var ba:ByteArray = bd.getPixels( bd.rect );
   ba.position = 0;
   byteArr = new ByteArray();

  //result will be in byteArr
  lib.encode(ba, byteArr, bd.width, bd.height, 100);,"NewFileName1.jpg");
encode( src:BimapData, image_data:ByteArrat, imageWidth:uint, imageHeight:uint, quality:int );


src:BitmapData - bitmapData to be encoded. cannot be null !
image_data:ByteArray - buffer where jpeg image will be written to. cannot be null !
imageWidth:int - 'src' image width
imageHeight:int - 'src' image height
quality:int - jpeg quality (1-100)

3.2 Or encode your image asynchronous
lib.encodeAsync( finish, bd, ba,bd.width, bd.height, 100, tuning:int );

encodeAsync( callback:Function, src:BimapData, image_data:ByteArrat, imageWidth:uint, imageHeight:uint, quality:int, tuning:int );


callback:Function - callback function to be called when compression is finished. function is invoked with out parameter, image_data byteArray (the same passed as a image_data parameter
src:BitmapData - see synchronous method
image_data:ByteArray - see synchronous method
imageWidth:int - see synchronous method
imageHeight:int - see synchronous method
quality:int - see synchronous method
tuning:int - this is most important parameter, it defines 'how often' method is going to interrupted and control flow returned to other parts of application. it should be interpreted, rather as a 'number of scanlines to be compressed in a single timeslice'

Flex Tutorial - An Asynchronous JPEG Encoder 
Alchemy - asynchronous jpeg encoding #2 
Alchemy - asynchronous jpeg encoding 
First I tried

No comments:

Post a Comment