I am using following function to Save the output from SWF and send it to a PHP page so that it creates JPG, my problem if there is not INTERNET connection and the SWF is in a CDROM can the Save function be used in FLASH so that it outputs JPG and save it on a computer.
In short can we Save movieclip output as an JPG
/**
Screenshot and jpg output
**/
import flash.display.BitmapData;
import flash.geom.Matrix;
//Buttons handlers. Should add an extra function because delegate doesn't allow to pass parameters
shaF.onPress = mx.utils.Delegate.create(this,makeShadow);
//Helper functions to pass parameters
function makeShadow() { capture(0) }
/*
create a function that takes a snapshot of the Video object whenever it is called
and shows in different clips
*/
function capture(nr){
this["snapshot"+nr] = new BitmapData(abc._width,abc._height);
//the bitmap object with no transformations applied
this["snapshot"+nr].draw(abc,new Matrix());
var t:MovieClip = createEmptyMovieClip("bitmap_mc"+nr,nr);
//positions clip in correct place
//t._x = 350; t._y = 10+(nr*130); t._xscale = t._yscale = 50
//display the specified bitmap object inside the movie clip
t.attachBitmap(this["snapshot"+nr],1);
output(nr);
//attachMovie("print_but", "bot"+nr, 100+nr, {_x:t._x+t._width+50, _y:t._y+t._height/2})
}
//Create a new bitmapdata, resize it 50 %, pass image data to a server script
// using a LoadVars object (large packet)
function output(nr){
//Here we will copy pixels data
var pixels:Array = new Array()
//Create a new BitmapData
var snap = new BitmapData(this["snapshot"+nr].width, this["snapshot"+nr].height);
//Matrix to scale the new image
myMatrix = new Matrix();
myMatrix.scale(1, 1)
//Copy image
snap.draw(this["snapshot"+nr], myMatrix);
var w:Number = snap.width, tmp
var h:Number = snap.height
//Build pixels array
for(var a=0; a<=w; a++){
for(var b=0; b<=h; b++){
tmp = snap.getPixel32(a, b).toString(16)
//if(tmp == "-fcffff")
//{
//tmp="-ff0000";
//}
pixels.push(tmp.substr(1))
}
}
//Create the LoadVars object and pass data to PHP script
var output:LoadVars = new LoadVars()
output.img = pixels.toString()
output.height = h
output.width = w
//The page (and this movie itself) should be in a server to work
output.send("show.php", "output", "POST")
}
stop()
Since you already have the BitmapData, this is fairly easy. Modifying your output function:
//Copy image
snap.draw(this["snapshot"+nr], myMatrix);
//Now check if we want to save as JPG instead of sending data to the server
if (runningFromCdrom) {
var encoder:JPEGEncoder = new JPEGEncoder();
var bytes:ByteArray = encoder.encode(snap);
var file:FileReference = new FileReference();
file.save(bytes);
} else {
// ...the rest of your output method...
}
How to determine the runningFromCdrom value is up to you. If the SWF is being run inside an HTML document, the best way to tell if the program is being run from a CD-ROM would be to specify it in the FlashVars.
Yes, you can save JPEG's directly from Flash. There is no need for the intermediate step to PHP.
You can use one of these JPEG encoders:
https://github.com/mikechambers/as3corelib
http://www.switchonthecode.com/tutorials/flex-tutorial-an-asynchronous-jpeg-encoder
I would recommend the second as it can work asynchronously (kind of) which means your UI shouldn't lock up while encoding the JPEG.
Related
Here is my dilemma. We use image stacks a lot here with alpha channels. I want to call up images in series using a slider. I am getting a concatenated string a pull up an image from my folder. But I can not get the images to load dynamically when I slide the slider bar.
I am using the frame number to change the file name to pull up the next frame. I can get the image to show up if I put the loader outside of the function, but when I put the loader in the function I get error after error saying the file cannot be located.
Here is the code as it currently stands :
var imgLoader = new Loader();
var str1 = String (".jpg");
var sliderValue:uint = mySlider.sliderKnob.x / 3;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event):void {
sliderValue = mySlider.sliderKnob.x / 3;
status_txt.text = "Slider position is: "+sliderValue;
fileText.text = "Sketch_0"+sliderValue+".jpg";
imgLoader.load( new URLRequest ( "Sketch_0"+sliderValue+".jpg"));
addChild(imgLoader);
setChildIndex(imgLoader, 0);
}
First thing up, you need to load one image without that slider stuff and see if it loads. Verify the paths if not. Relative paths, as you put them, will work relatively to the folder where SWF is (or where the HTML page, containing the SWF, is).
Second, relieve the heavy burden you are trying to put on the Flash Player.
addEventListener(Event.ENTER_FRAME, onFrame);
var nextName:String;
function onFrame(e:Event):void
{
var anIndex:int = mySlider.sliderKnob.x / 3;
var aName:String = "Sketch_0" + anIndex + ".jpg";
status_txt.text = "Slider position is: " + anIndex;
fileText.text = aName;
// Flash Player does not load images instantly,
// so lets request new image only if user stopped moving the slider.
if (aName == nextName)
{
loadNext(nextName);
}
else
{
nextName = aName;
}
}
var currentName:String;
var currentImage:Loader;
function loadNext(value:String):void
{
// If the requested file is the same as current, just ignore the request.
if (value == currentName) return;
currentName = value;
// Dispose of the previous image in a proper way.
if (currentImage)
{
removeChild(currentImage);
currentImage.unloadAndStop(true);
currentImage = null;
}
// Create a new one.
var aRequest:URLRequest = new URLRequest(currentName);
currentImage = new Loader();
currentImage.load(aRequest);
addChild(currentImage);
}
I have an RTMP stream that I need to take a screenshot of. I got a security error using bitmapData.draw() since it was coming from AWS S3 so I found a workaround that allows me to take a screenshot of the video:
var bitmap = new Bitmap();
var graphicsData : Vector.<IGraphicsData>;
graphicsData = container.graphics.readGraphicsData(); //-- container is a sprite that holds my video element
bitmap.bitmapData = GraphicsBitmapFill(graphicsData[0]).bitmapData;
var image:ByteArray = new JPGEncoder(85).encode(bitmap.bitmapData);
At this point, I send the ByteArray to PHP, create a JPG out of the ByteArray and save it to the server. That all works great.
The issue is I apply filters realtime to the container sprite which alters the look of the video like brightness, contrast, saturation etc, but when saving to the server, the saved image doesn't contain the filters I had applied.
I tried reapplying the filters to bitmap, graphicsData and bitmap.bitmapData, but nothing worked.
How can I either retain the filters applied or reapply the filters to the above code?
EDIT
Here is how I initially apply the filters:
private function applyEffects(effects:Array):void
{
currentEffects = effects;
var props:Object = {};
for (var i:String in effects)
{
props[effects[i].effect] = effects[i].amount;
}
TweenLite.to(container,0,{colorMatrixFilter:props});
}
props object could look something like: {contrast:0.5,saturation:1}
Ok, I have solved this on my own with a little suggestion Jack Doyle (GSAP Author) gave me. I have described what I did differently in the comments of my code:
var graphicsData:Vector.<IGraphicsData>;
graphicsData = container.graphics.readGraphicsData();
var origBitmap:Bitmap = new Bitmap();
origBitmap.bitmapData = GraphicsBitmapFill(graphicsData[0]).bitmapData;
//-- at this point I have a screenshot of the video
var props:Object = {};
for (var i:String in currentEffects)
{
props[currentEffects[i].effect] = currentEffects[i].amount;
}
TweenLite.to(origBitmap,0,{colorMatrixFilter:props});
//-- at this point I've reapplied the effects.
//-- originally, sending bitmap.bitmapData to the encoder didn't retain the filters so I went 1 step further
//-- create a new bitmapData and draw the reapplied filter'd bitmap
var filteredBitmapData:BitmapData = new BitmapData(640,360);
var filteredBitmap:Bitmap = new Bitmap(filteredBitmapData);
filteredBitmapData.draw(origBitmap);
//-- encode the new bitmap data
var image:ByteArray = new JPGEncoder(85).encode(filteredBitmapData); //-- filteredBitmapData is now filtered and I can send this to the server
I am attempting to use the 'File' function in ActionScript 3 to save the following information:
I have varying draggable display objects in the scene, the amount and type can vary. I want to save the amount and their position and then load them back in a future session.
I am struggling to use File to save anything, I have searched the Adobe documentation and cannot get my head round how to use it.
I have not yet developed any code using it.
Any help would be appreciated.
Thank you.
You are trying to write a DisplayObject into the file directly, this is prevented by Flash engine due to the way Flash handles default serialization of any object. In order to save a DisplayObject into the external resource, you need to employ IExternalizable on that object's class and any class of objects you will plan to store as well. The implementation of writeExternal should save all data required to rebuild the said object from scratch, and readExternal should also employ methods to restore the integrity of said DisplayObject by performing addChild() on nested display objects, or adding them into other internal structures that object might contain.
Note, other answers contain valid points for doing a custom serialization with XML or JSON, and also contain links to requires import, in particular, flash.utils.registerClassAlias and flash.utils.getDefinitionByName are gravely needed to recreate the structure from a serialized data chunk.
An example: Let's say you have a drawing board in a Board class, and a set of rectangles that you can drag by using mouse, that differ by size and color. Rectangles are custom made MovieClips and don't have a class of their own, but each MovieClip is also assigned a color property to simplify their distinction. This means you need to implement IExternalizable on Board class only. Let's also assume Board class has a pieces array that contains all links to nested rectangles, and a method to create a new properly sized rectangle based on width, height and color supplied as parameters. (There might be more requirements to the data structure of Board to meet in your case, so watch closely) So, the process of serializing Board will be to collect all the data from nested MCs and stuff it in order into IDataOutput supplied, and the process of restoring an instance of Board should retrieve stored data, parse it to find what is where, create the nested MCs to be the same like they've been stored, position them properly, addChild() to self and rebuild thepieces` array.
public class Board extends Sprite implements IExternalizable {
private var pieces:Array;
public function createRectangle(_width:Number,_height:Number,color:uint):MovieClip {
var mc:MovieClip=new MovieClip();
mc.graphics.beginFill(color);
mc.graphics.drawRect(0,0,_width,_height);
mc.graphics.endFill();
mc.color=color;
pieces.push(mc);
return mc;
}
A refinement to data structure is already visible - you need to store the passed _width and _height in the MC somewhere, because the actual width of that MC will differ from what's passed by the default line thickness (1, 0.5 on either side). x and y are properly retrieved from MC's properties, though. So, adding both lines into createRectangle is necessary.
mc._width=_width;
mc._height=_height;
With this, serializing the Board becomes more easy.
public function writeExternal(output:IDataOutput):void {
var pl:int=pieces.length; // cache
output.writeInt(pl); // assuming we keep this array in integral state
for (var i:int=0;i<pl;i++) {
var _mc:MovieClip=pieces[i];
output.writeDouble(_mc.x); // this is usually not rounded when dragging, so saving as double
output.writeDouble(_mc.y);
output.writeDouble(_mc._width);
output.writeDouble(_mc._height);
output.writeInt(_mc._color);
}
// if anything is left about the "Board" itself, write it here
// I'm assuming nothing is required to save
}
To restore, you need to read the data out of IDataInput in the very same order as it was written in writeExternal and then process to rebuilding the display list we've stored.
public function readExternal(input:IDataInput):void {
// by the time this is called, the constructor has been processed
// so "pieces" should already be an instantiated variable (empty array)
var l:int;
var _x:Number;
var _y:Number;
var _width:Number;
var _height:Number;
var _color:uint;
// ^ these are buffers to read data to. We don't yet have objects to read these into
input.readInt(l); // get pieces length
for (var i:int=0;i<l;i++) {
input.readDouble(_x);
input.readDouble(_y);
input.readDouble(_width);
input.readDouble(_height);
input.readInt(_color);
// okay we got all the data representing the rectangle, now make one
var mc:MovieClip=createRectangle(_width,_height,_color);
mc.x=_x;
mc.y=_y;
addChild(mc); // createRectangle does NOT have addchild call
// probably because there are layers for the parts to be added to
// I'm assuming there are no layers here, but you might have some!
// pieces array is populated inside createRectangle, so we leave it alone
}
// read all the data you have stored after storing pieces
}
In case your nested MCs have a class that also implements IExternalizable, you can save the entire array in a single instruction, writeObject(pieces), this will make Flash walk through the array, find all data it contains and call writeObject on any nested object, essentially calling that class's writeExternal function for each of the instance in the array. Restoring such an array should include rebuilding the display list by walking the array and calling addChild() on each of the restored instances.
And last but not the least, registerClassAlias() should be called prior to doing any serialization or deserialization of custom objects. Best place to call these is probably your main object's constructor, as this will surely be called before any other code your application contains.
Assuming all your objects to save belong to the same parent, you could dosomething along these lines:
First, create a class file (let's call is SaveData.as and put it in the root of your project directory). This will describe the data you want to save:
package
{
import flash.geom.Rectangle;
public class SaveData
{
public var bounds:Rectangle; //to save where an object is on the stage
public var classType:Class; //to save what kind of object it is
//you could add in more proterties, like rotation etc
public function SaveData() {
}
}
}
Next, on your save function, do something like this:
//this will hold all your data
//a vector is the same as an array only all members must be of the specified type
var itemList:Vector.<SaveData> = new Vector.<SaveData>();
//populate the array/vector with all the children of itemContainer
var tmpItem:SaveData;
//loop through all children of item container
for (var i:int = 0; i < itemContainer.numChildren; i++) {
tmpItem = new SaveData(); //create a new save record for this object
tmpItem.bounds = itemContainer.getChildAt(i).getBounds(itemContainer); //save it's bounds
tmpItem.classType = getDefinitionByName(itemContainer.getChildAt(i)) as Class; //save it's type
itemList.push(tmpItem); //add it to the array
}
//Now you have an array describing all the item on screen
//to automatically serialize/unserialize, you need this line (and you need to register every class nested in SaveData that isn't a primitive type - which would just be Rectangle in this case
registerClassAlias("SaveData", SaveData);
registerClassAlias("flash.geom.Rectangle", Rectangle);
//create a new File to work with
var file:File = File.applicationStorageDirectory; //or whatever directory you want
file.resolvePath("saveData.data"); //or whatever you want to call it
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeObject(itemList); //write the array to this file
fileStream.close();
Now, to load it back in:
var itemContainer:Sprite = new Sprite(); //however you initialize this
addChild(itemContainer);
var file:File = File.applicationStorageDirectory;
file.resolvePath("saveData.data");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var itemList:Vector.<SaveData> = fileStream.readObject() as Vector.<SaveData>;
fileStream.close();
//now that you've read in the array of all items from before, you need to recreate them:
var tmpItem:DisplayObject;
var tmpClass:Class;
//loop through all items in the array, and create a object
for (var i:int = 0; i < itemList.length; i++) {
tmpClass = itemList[i].classType; //The type of item
tmpItem = new tmpClass() as DisplayObject; //create the item
//now move the item to it's former position and scale
tmpItem.x = itemList[i].x;
tmpItem.y = itemList[i].y;
tmpItem.width = itemList[i].width;
tmpItem.height = itemList[i].height;
//add the item back to the parent
itemContainer.addChild(tmpItem);
}
If you're not sure of the imports, here they are:
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.registerClassAlias;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
var bytes:ByteStream;
var filename:String = "mySaveFile.sav";
//[...] //initialize byte stream with your data
//get a reference to where you want to save the file
//(in this example, in the application storage directory,
//which is fine if you don't need to move the save file between computers
var outFile:File = File.applicationStorageDirectory;
outFile = outFile.resolvePath(fileName);
//create a file output stream, which writes the byte stream to the file
var outStream:FileStream = new FileStream();
outStream.open(outFile, FileMode.WRITE);
outStream.writeBytes(bytes, 0, bytes.length);
outStream.close();
//to load the file:
var inFile:File = File.applicationStorageDirectory;
inFile = inFile.resolvePath(fileName);
bytes = new ByteArray();
var inStream:FileStream = new FileStream();
inStream.open(inFile, FileMode.READ);
inStream.readBytes(bytes);
inStream.close();
I usually use SharedObject, by saving the number of objects with their locations ,scale ,rotation , .. etc. as an array (usually multidimensional array).
this example is tested :
first make a movie clip giving it "mc" as a name in the ActionScript Linkage
add any graphics you like
(this MovieClip will be the objects to be saved later )
then add the following script
////////// get random values for each object
var speed:Number ;
var yPosition:Number ;
var size:Number ;
this.width = size;
this.height = size;
this.y = yPosition ;
//// Moving the MovieClip from Left to right
function moving(e:Event):void
{
this.x += speed ;
if(this.x > 550)
{
this.removeEventListener(Event.ENTER_FRAME,moving);
MovieClip(parent).removeChild(this);
}
}
this.addEventListener(Event.ENTER_FRAME,moving);
in the root stage of the project add :
import flash.events.MouseEvent;
import flash.display.MovieClip;
var num:int = 0 ;
var mmc:MovieClip ;
var mySharedObj:SharedObject = SharedObject.getLocal("SavingStatus"); //// SharedObject to save info
function init()
{
if (!mySharedObj.data.savedArray)
{
///// first run No datat saved
this.addEventListener(Event.ENTER_FRAME,addingmcs)
}else {
///// Laoding previusly saved data
loading();
}
}
init() ;
/////////////// adding MovieClips to stage /////
function addingmcs(e:Event):void
{
num +=1 ;
if(num > 20){
num = 0 ;
mmc = new mc ;
mmc.speed = 2 + (5 * Math.random()) ;
mmc.yPosition = 500 * Math.random() ;
mmc.size = 50 + 10 * Math.random() ;
this.addChild(mmc);
}
}
///////////////////////////////////////////
///////////////////////////////////////////////
var obj:* ; //// to hold children MovieClips of the stage
var savingArr:Array = new Array ; //// the array to be saved , Contains all info of the children
////////////// Save all MovieClips with their parameters ////////////
function saving(e:MouseEvent):void
{
this.removeEventListener(Event.ENTER_FRAME,addingmcs)
for (var i:int=0;i<this.numChildren;i++)
{
if (this.getChildAt(i)is MovieClip) { ///// add all MovieClips of the stage to the array with their info (position - size - speed ... etc)
obj = this.getChildAt(i);
savingArr.push([obj , obj.x , obj.y , obj.speed , obj.size]); //// add the info in 3 dimentional array
obj.speed = 0 ;
}
}
////////////////saving array externally
mySharedObj.data.savedArray = savingArr ;
mySharedObj.flush ();
}
save_btn.addEventListener(MouseEvent.CLICK,saving)
////////////// Load all saved parameters ////////////
load_btn.addEventListener(MouseEvent.CLICK,loading)
function loading(e:MouseEvent =null):void
{
savingArr = mySharedObj.data.savedArray ;
for (var i:int=0;i<savingArr.length ; i++)
{
mmc = new mc ;
mmc.x = savingArr[i][1] ; ///// Get saved x
mmc.yPosition = savingArr[i][2] ; ///// Get saved y
mmc.speed = savingArr[i][3] ; ///// Get saved speed
mmc.size = savingArr[i][4] ; ///// Get saved size
addChild(mmc);
}
this.addEventListener(Event.ENTER_FRAME,addingmcs) ;
}
You already have some answers here but from your question, maybe you are missing the larger context.
So the File class represents a path to a file on disk and the FileStream class enables reading and writing data to that file. These are easy to use and there are many examples on the web. Here is one tutorial from Adobe: Reading and writing files
But what data to write and what is the format and data type? Those are the more important and more interesting questions.
The simplest approach is to use a text based format like XML or JSON where you read and write whatever properties of Sprites (or other objects) you want. One advantage of this is that the resulting file is a human readable/editable text file. A minor disadvantage is that you need to specify which properties to save and restore and deal with simple data type conversions (string to int, etc).
A more robust approach is to use what is called Serialization where the state of an entire object is saved and restored. This is more complicated and while not hard, is probably overkill for your project needs. There are good examples and discussion here , here and here.
For your current project and skill level, I'd suggest using XML orJSON Here's a tutorial using XML: Loading and Processing External XML Files
I have come a little closer with my project, and still need some help please. I have 5 Flvs which i want to play randomly on this page www.music-puppets.com/
The .fla file I have created contains this code:
var files:Array = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ];
var shuffledFiles:Array = shuffleArray(files);
//quick test
var testTimer:Timer = new Timer(1000);
testTimer.addEventListener(TimerEvent.TIMER,updateFile);
testTimer.start();
function updateFile(event:TimerEvent):void{
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files); //all files played, repeat process
trace('play file',shuffledFiles[0]);
shuffledFiles.shift();
}
function shuffleArray(source:Array,clone:Boolean = true):Array {
var output:Array = [];
var input:Array = clone ? [].concat(source) : source; //clone ? preserve orignal items by making a copy for shuffling, or not
while(input.length) output.push(input.splice(int(Math.random() * input.length-1),1) [0]);
return output;
}
This script works. In the Output every flv is listed randomly, and then repeated. Next up i want this AS Script to work with an FLV Component.
But how to I get that to work?
In my library I have the 5 flvs, and flvplayback component.
I dragged the FLVPlayback component to the stage, but I can only add one flv in the source. How do I get my working actionscript to work with the FLVPlayback component.
Here you can see how my screen looks like.
capture01.jpg
capture02.jpg
Would be great to get some feedback :)
First of all you need to give your FLVPlayback component an instance name using the properties panel. That will let you talk to it from the code.
Next you will need to add a listener to the FLVPlayback component to detect when each video finishes. Let's assume you've given it an instance name of myVideo:
myVideo.addEventListener(VideoEvent.COMPLETE,onVideoComplete);
You will need a handler function for this, and that will look similar to the function you currently use for each iteration of your timer:
function onVideoComplete(event:VideoEvent):void {
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files); //all files played, repeat process
myVideo.source = shuffledFiles.shift(); //grab the first array item to play in the FLVPlayback component
}
Finally, make sure that your FLVPlayback component is set to play a new source automatically, then assign the first video to get things going:
myVideo.autoPlay = true;
myVideo.source = shuffledFiles.shift();
If anyone is interested. I have got the running code :)
import flash.events.Event;
import fl.video.*;
var files:Array;
var shuffledFiles:Array;
loaderInfo.addEventListener(Event.COMPLETE,ready);
function ready(event:Event):void{
loaderInfo.removeEventListener(Event.COMPLETE,ready);
//swf rescale setup
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE,stageResized);
//get FlashVars - a string converted into an Array by spliting it on the , character
//if the files FlashVar is setup correctly use the data, else use default values
if(loaderInfo.parameters.files != undefined) files = loaderInfo.parameters.files.indexOf(',') > 0 ? loaderInfo.parameters.files.split(",") : [loaderInfo.parameters.files];
else files = [ "Sz01Puppet.flv", "Sz02Puppet.flv", "Sz03Puppet.flv", "Sz04Puppet.flv", "Sz05Puppet.flv" ];
shuffledFiles = shuffleArray(files);
//play the 1st video
videoPlayer.source = shuffledFiles[0];
shuffledFiles.shift();
//see when the video finished playing
videoPlayer.addEventListener(VideoEvent.COMPLETE,videoFinished);
}
function videoFinished(event:VideoEvent):void{
if(shuffledFiles.length == 0) shuffledFiles = shuffleArray(files);//all files played, repeat process
videoPlayer.source = shuffledFiles[0];//play the first video in the random list
videoPlayer.play();
trace('playing',shuffledFiles[0]);
shuffledFiles.shift();//remove the first video from the random list (e.g. [2,0,1].shift() becomes [0,1])
}
function stageResized(event:Event):void{
videoPlayer.width = stage.stageWidth;
videoPlayer.height = stage.stageHeight;
}
function shuffleArray(source:Array,clone:Boolean = true):Array {
var output:Array = [];
var input:Array = clone ? [].concat(source) : source;//clone ? preserve orignal items by making a copy for shuffling, or not
while(input.length) output.push(input.splice(int(Math.random() * input.length-1),1)[0]);
return output;
}
i'm trying to duplicate a swf loaded using greensocks LoaderMax but i don't seem to be able to
i'm using the following code:
private var _assetCache : Dictionary;
public function getAssetById(assetId:String):DisplayObject
{
var asset:DisplayObject;
if (!_assetCache[assetId])
{
_assetCache[assetId] = LoaderMax.getContent(assetId).rawContent;
}
asset = _assetCache[assetId];
// duplicate bitmap
if (asset is Bitmap)
{
var bmd:BitmapData = new BitmapData(asset.width, asset.height, true, 0);
return new Bitmap(bmd, "auto", true);
}
// otherwise return
return SpriteUtils.duplicateDisplayObject(asset);
//return asset; // if previous line is commented out, this works well but there will be only a single copy of the loaded swf, kinda negating the use of a cache
}
and this is SpriteUtils.duplicateDisplayObject(asset) (taken from this
static public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject
{
// create duplicate
var targetClass:Class = Object(target).constructor;
var duplicate:DisplayObject = new targetClass();
trace(duplicate, duplicate.height); // traces [MovieClip, 0]
// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid)
{
var rect:Rectangle = target.scale9Grid;
// WAS Flash 9 bug where returned scale9Grid is 20x larger than assigned
// rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
duplicate.scale9Grid = rect;
}
// add to target parent's display list
// if autoAdd was provided as true
if (autoAdd && target.parent)
{
target.parent.addChild(duplicate);
}
return duplicate;
}
if i simply return the asset from _assetCache (which is a dictionary) without duplicating it, it works and traces as a MovieClip but when i try to duplicate it, even though the traces tell me that the duplicate is a movieclip. Note the clip being loaded is a simple vector graphic on the stage of the root of the timeline
thanks in advance
obie
I don't think simply calling the constructor will work.
Try doing this (I've assumed certain previous knowledge since you're able to get rawContent above):
1) Load the data in using DataLoader in binary mode.... in the context of LoaderMax it would be like: swfLoader = new LoaderMax({name: "swfLoader", onProgress:swfProgressHandler, onChildComplete: swfLoaded, auditSize:false, maxConnections: 2}); swfLoader.append(new DataLoader(url, {format: 'binary'})); (the main point is to use DataLoader with format='binary')
2) Upon complete, store the ByteArray which this returns into your dictionary. The first part of your above code will basically be unchanged, though the bytearray might be in content rather than rawContent
3) Whenever you need a duplicate copy, use Loader.loadBytes() on the ByteArray. i.e. var ldr:Loader = new Loader(); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, swfReallyLoaded); ldr.loadBytes(_assetCache[assetId]);
As with all loading, you might need to set a LoaderContext, and if in AIR- allowLoadBytesCodeExecution = true; allowCodeImport = true;