Do you ever have nightmares where you are back in the Actionscript 2 days and trying to save BitmapData to a JPEG? ... ok, so maybe its just me, but who cares because it's easy now!
Old news...ByteArray rocks! If you aren't familiar, it was introduced in AS3 for playing with binary data and has endless uses. Compression being the most obvious, but speed, custom protocols, and streaming data are no less important. zlib and deflate support are built in as well.
Capturing BitmapData, encoding it as a JPG, and saving it through Rails...Step 1. We need to download the as3corelib. The library we will be using from this package is com.adobe.images.JPGEncoder (a port of this C algorithm), but look around! There are some awesome libraries in here.
Some imports...
1 import flash.display.MovieClip; 2 import flash.display.Stage; 3 import flash.display.Bitmap; 4 import flash.display.BitmapData; 5 import flash.utils.ByteArray; 6 import com.adobe.images.JPGEncoder; 7 import flash.events.*; 8 import flash.net.*;Capture BitmapData, encode as a JPG, convert to ByteArray, send to Rails
1 // Capture the BitmapData of the stage for example 2 var stage_snapshot:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight); 3 stage_snapshot.draw(stage); 4 5 // Setup the JPGEncoder, run the algorithm on the BitmapData, and retrieve the ByteArray 6 var encoded_jpg:JPGEncoder = new JPGEncoder(100); 7 var jpg_binary:ByteArray = encoded_jpg.encode(stage_snapshot); 8 9 var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream"); 10 var request:URLRequest = new URLRequest("/generate_jpg"); 11 request.requestHeaders.push(header); 12 request.method = URLRequestMethod.POST; 13 request.data = jpg_binary; 14 15 var loader:URLLoader = new URLLoader(); 16 loader.load(request);Rails n' RMagick...
1 // Example RMagick usage... 2 image = Magick::Image.from_blob(request.body.read).first 3 image.write("#{RAILS_ROOT}/public/jpgs_from_as/test.jpg") Why it rocks...Well, just think about what you would have to do without it?
Data transfer - 800x600 sized image...480000 pixels...*~4 (RGBA)...~2Megs? For a ~80kb compressed jpg? No dice.
Data processing - calculating this per pixel color array makes your machine sound like a lawnmower...
I suppose I'll miss dealing with color palettes and encoding pixel data...NOT!
by Genís