Using JPGEncoder without stalling

Was racking my head against my desk today trying to figure this out.

I’m using JPGEncoder from AS3CoreLib to properly encode and save images with Air and realized that the app was stalling during JPGEncoder’s encode().

Fortunately, a fellow forum member at actionscript.org, Jerion, had also experienced this and wrote a simple fix – use events!

Here’s the how to use JPGEncoder as originally designed:

package {
	...
	import com.adobe.images.JPGEncoder;
	...
	public class ImageSaver() {
		...
		public function saveImage(bitmapData):void {
			var jpgEncoder:JPGEncoder = new JPGEncoder(85);

			// application stalls until the following line is complete
			var jpgStream:ByteArray = jpgEncoder.encode(bitmapData);

			// continues fine from here...
			var imageFile:File = File.desktopDirectory.resolvePath("imagesFolder");

			try {
				var filestream:FileStream = new FileStream();
				filestream.open(imageFile,FileMode.WRITE);
				filestream.writeBytes(jpgStream);
				filestream.close();
			} catch(e:Error) {
				trace("Error saving image: " + e)
			}
		}
		...
	}
}

Works great, but everything in the application stops while jpgEncoder.encode() is run. If the image is large, the user experiences a “halted” application. In my case, I’m looping many small images, and the experience is a constant “stutter” as the images are looped. Nicely animated preloaders become stop animations.

The solution is to rewrite JPGEncoder so that it fires an event when it is done encoding.

Simply download this new JPGEncoder code and replace the original from AS3CoreLib – again, a special thanks to Jerion for coding this!

Once replaced, here’s what the new encode code would look like, and the app just runs along nice and smooth!

package {
	...
	import com.adobe.images.JPGEncoder;
	...
	public class ImageSaver() {
		...
		private var _bitmapData;
		...
		public function saveImage(bitmapData):void {
			_bitmapData = bitmapData;

			var jpgEncoder:JPGEncoder = new JPGEncoder();
			jpgEncoder.addEventListener("ImageDone",imageEncodeComplete);
			jpgEncoder.encode(_bitmapData,85);
		}
		private function imageEncodeComplete(evt:Event):void {
			var jpgStream:ByteArray = evt.currentTarget.imageBytes;
			var imageFile:File = File.desktopDirectory.resolvePath("imagesFolder");

			try {
				var filestream:FileStream = new FileStream();
				filestream.open(imageFile,FileMode.WRITE);
				filestream.writeBytes(jpgStream);
				filestream.close();
			} catch(e:Error) {
				trace("Error saving image: " + e)
			}
		}
		...
	}
}


  1. michael on Friday 24, 2009

    thank you,

    this helps big time !!..

    respect