Search code examples
actionscriptbitmapsaveencoder

Actionscript 3 Load> Combine> and Save External Images


I'm new to actionscript 3, So Thank you in advance for any help you can give. Bascially what I'm trying to do is load 2 or more external images, all the same size and resolution, then combine or composite them one on top of the other, then save that result as a new image using a jpeg or png encoder.

I don't want to take a snapshot of the stage, I'd like to save the images with thier original resolution. So far the only thing I've been able to do is load two images, and composite them on the stage. thats about it.

Can someone please give some insight into how to accomplish this. I'm using flash pro CS5.5, and writing code in a class file, not on the timeline. Here is a copy of the code.

package 

{

import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.*;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;


public class imageComposite extends MovieClip
{

    var images:Array = ["koala.png","koala2.png"];//two images

    public function imageComposite()
    {
        // constructor code
        var thumbLoader:Loader;

        for (var i:uint = 0; i < images.length; i++)
        {

            thumbLoader = new Loader;
            thumbLoader.load(new URLRequest(("assets/" + images[i])));
            addChild(thumbLoader);
        }
        thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,bmpData);
    }


    public function bmpData(evt:Event):void
    {

        trace("Event was completed successfully!");
    }


}

}


Solution

  • First you put both the Loader objects into a separate "holder" object.

    // constructor code
    var holder:Sprite = new Sprite();
    addChild(holder);
    
    var thumbLoader:Loader;
    
    for (var i:uint = 0; i < images.length; i++)
    {
    
        thumbLoader = new Loader;
        thumbLoader.load(new URLRequest(("assets/" + images[i])));
        holder.addChild(thumbLoader);
    }
    ...
    

    Later in your "complete" event handler:

    var bitmapData:BitmapData = new BitmapData(holder.width, holder.height, false);
    bitmapData.draw(holder);
    
    var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
    

    Then you can write this byteArray object to the server or to disk (desktop AIR application).