Thursday, January 27, 2011

How to use Flash Actionscript to save a MovieClip or Sprite to JPEG file:

Have you ever wonder how you can use Flash actionscript to save images?  Well, it is quite easy and below is the code you will need for doing so, more specifically, it will allow you to save MovieClip or Sprite to JPEG.

In order to do this, you will need the as3corelib and the save function in FileReference class requires minimum Flash Player 10 or Air 1.5.
 



import flash.errors.IllegalOperationError;
import flash.errors.MemoryError;
import flash.net.FileReference;
import com.adobe.images.JPGEncoder;

/**
 * This function saves a movieclip to a jpeg.
 *
 * @param    image        the movieclip.
 * @param    imageName    the name that will be saved for this jpeg.
 */
function saveImage( image:MovieClip, imageName:String ) : void {
    try {
    // create a copy of the image
        var jpgSource:BitmapData = new BitmapData( image.width, image.height );
        jpgSource.draw(image);
    // encode it to jpeg and convert it to byte array
        var jpgEncoder:JPGEncoder = new JPGEncoder(85);
        var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
    // create a file reference to save the byte array
    // this will save the image to ".jpg"
        var file:FileReference = new FileReference();
        file.addEventListener( IOErrorEvent.IO_ERROR, ioErrorHandler );
        file.save( jpgStream, imageName );
    }
    catch( ioe:IllegalOperationError ) {
        trace("Illegal operation.");
    }
    catch( ae:ArgumentError ) {
        trace("Invalid argument.");
    }
    catch( me:MemoryError ) {
        trace("Insufficient memory.");
    }
    catch( error:Error ) {
        trace("Error trying to save image : " + imageName 
              + " . Error : " + error);
    }
}

/**
 * Handles IOErrors.
 */
function ioErrorHandler( event:IOErrorEvent ) : void {
    trace("ioErrorHandler: " + event);
}

Related Links:
    

2 comments: