Encoding JPEGs client-side in AS3

Technology

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)

Comments are closed.

Discuss this article with the rest of the community on our Discord server!
Tagged

ADVERTISEMENT

Maker Faire Bay Area 2023 - Mare Island, CA

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 15th iteration!

Buy Tickets today! SAVE 15% and lock-in your preferred date(s).

FEEDBACK