Download

This is an example of encoding an JPEG by using the Alchemy JPEG Encoder while monitoring the progress. Read more about it in the post about Using the fast asynchronous Alchemy JPEG encoder in Flash.

Source

The source code requires the following objects to be placed on the stage in the Flash file:

  • A MovieClip instance with graphics (for the image) named myGraphic.
  • A ProgressBar component instance named progressBar.
  • A Button component instance named btnSave.

Source code from the main timeline in alchemy-jpeg-example.fla

// BitmapData for image
import flash.display.BitmapData;
 
// Alchemy JPEG library
import cmodule.jpegencoder.CLibInit;   
 
/// Init alchemy object
var jpeginit:CLibInit = new CLibInit(); // get library obejct
var jpeglib:Object = jpeginit.init(); // initialize library exported class  
 
// Set up save button
// Make it disabled until encoding is complete
btnSave.enabled = false;
btnSave.addEventListener(MouseEvent.CLICK, 
	function() {
		// Save the data to a local file
		// The FileReference save must be called within an CLICK event
		var filesave:FileReference = new FileReference();
		filesave.save(imgEncoded, "My Image.jpg");
	}
);
 
 
// Set up an image to save
var imgBitmap:BitmapData = new BitmapData(myGraphic.width, myGraphic.height, false, 0xFFFFFF);
// Draw the graphics onto the BitmapData object
imgBitmap.draw(myGraphic);
 
// Prepare Alchemy objects
var imgData:ByteArray = imgBitmap.getPixels(imgBitmap.rect);
var imgEncoded:ByteArray = new ByteArray();
imgData.position = 0;
 
// Set up progressbar for manual progress
progressBar.mode = "manual";
 
// Encoding progress monitor function
var encodeProgress:Function = function() {
	// Listen to the position of the data reader
	trace("Encoding progress: " + Math.round(imgData.position/imgData.length*100) + "%");
	progressBar.setProgress(imgData.position, imgData.length); 
};
// Start monitoring the progress of the encoding
var progressMonitor:Number = setInterval(encodeProgress, 20);
 
// Encoding progress complete function
var encodeComplete:Function = function() {
	trace("Encoding complete");
 
	// Stop monitoring the progress
	clearInterval(progressMonitor);
 
	// Set the progressbar to 100%
	progressBar.setProgress(imgData.position, imgData.length);
 
	// Enable the saving button
	btnSave.enabled = true;
};
 
// Start JPEG encoder
trace("Start encoding");
var jpegQuality:Number = 80;
jpeglib.encodeAsync(encodeComplete, imgData, imgEncoded, imgBitmap.width, imgBitmap.height, jpegQuality);