Encoding JPEGs client-side in AS3

I've been doing a bunch of Flash Actionscript 3 development lately at work, and one of my favorite features with the new drawing API is the ease and speed with which you can rasterize vector data and manipulate image bitmaps.

What's killer is that Adobe's as3corelib addon library finally gives us some essential tools that have been sorely lacking, none the least of which is a client side JPEG encoder. With this, you can turn any drawable object like a sprite or a movieclip into a ByteArray holding the compressed JPEG data in just a few lines of code. It's as simple as this:

import com.adobe.images.JPGEncoder;

var clipbmp:BitmapData = new BitmapData (aclip.width, aclip.height);
clipbmp.draw(aclip);

var jpgEnc:JPGEncoder = new JPGEncoder(90);
var jpgbytes:ByteArray = jpgEnc.encode(clipbmp);

This turns the "aclip" sprite or movieclip into a rasterized, flattened, BitmapData object. The BitmapData is then run through the JPEG encoder with the quality setting of 90 and you're left with the raw JPEG-compressed image in a ByteArray object. The as3corelib also provides a PNG encoder, with which you can just use the static method PNGEncoder.encode(clipbmp).

This is perfect for saving a capture of user-generated artwork to the server. Just set the data member of a URLRequest object to the ByteArray and post it. For more detailed information on how to put all the pieces together, Henry Jones has a really thorough post of compressing JPEG data and pinging it off a server to force an image download.

Unfortunately, to trigger a JPEG download, you still need to post the image data up to a server script and have it echo it back to the browser. The difference now, though, is that you can do the compression on the client end, saving both server CPU time and the time to upload the image data. This means saving a large image is a few second process instead of taking a minute and a half.

Actionscript 3 Core Library (as3corelib)

Posted by Jason Striegel | Apr 22, 2008 10:03 PM
Flash, Software Engineering, Web | Permalink | Comments (2) Bookmark and Share

Recent Entries

Comments

Newest comments listed first.

Posted by: todd anderson on April 23, 2008 at 6:57 AM

Part of Flex 3 SDK also

If you are using the Flex 3 SDK, you no longer have to use the classes from the corelib as the JPEGEncoder and PNGEncoder are now part of the SDK in the mx.graphics.codecs package.


Posted by: The Internet on April 24, 2008 at 7:11 PM

Enough Already!

Flash apps r a waste of time & effort and a scourge of the internet. Learn how to code in a real language or stick to designing unusable interfaces and 'eff off. Bitches!


Leave a comment



Bloggers

Welcome to the Hacks Blog!

Brian Jepson.Brian Jepson


Jason Striegel.Jason Striegel


Philip Torrone.Phillip Torrone



See all of the books in the Hacks Series!
Advertise here.

Recent Posts

www.flickr.com
photos in Hacks More photos in Hacks