Duplicate Movieclip Flash Action Script Enhanced
Hi Guys, finally after a long time i have found some time to update the duplicate process for flash. It was prity strange why even in action script 3 there is no clone method. Any ways i have devised my own strategy for doing that.
To duplicate movieclip objects in flash as3 is realy easy. All you have to do is create a class against a movie clip and instantiate objects of that class and keep adding the objects on to Stage.
In the example attached I have created 3 display objects mcP1,mcP2 and mcP3 also i have associated these objects with 3 classes mcP1.as, mcP2.as and mcP3.as.
Now once this is done when you click on the generate button code randomly creates object of mcP1.as, mcP2.as and mcP3.as class and add them on to the stage.
This will duplicate the objects and perhaps the easiest way to duplicate objects in action script 3 and onwards. Easy !
I hope to will solve your purpose. Looking forward for your feed back. Thank you.
Working sample can be viewed on the following link.
Awaiting feed back on this. Thank you
XML and Flash Image Slide Show Enhanced
Hi , Guys i have been listening most of the comments. Busy schedual never allowed me to actually upgrade the code.
Here is the new enhanced code for image slide show using flash and XML. Well after getting feed back on the first code and listening to some requirements following enhancements have been made.
1- Memory optimization.
2. More use of swap child.
3. Image Loader class added in to the system.
4. Optimized code.
5. Logo option.
6. Linked images to urls
7. Improved transitions code
I hope to will solve your purpose. Looking forward for your feed back. Thank you.
Working sample can be viewed on the following link.
Awaiting feed back on this. Thank you
Flash XML Image Slide Show Action Script 3
Hi, every one. I got many queries to write an article regarding How to create Image Slide Shows. Slide shows also referred as web slideshow or web slide shows can be made using java script and Flash. I prefer Flash action script Image Slide Shows over Javascript image slide shows.
Reason for that is with flash we can have variety of flash animations and effects available in action script api. Also we can make our customized flash animated effects. In java script we are very limited in terms of transitions and effects during the image slide show. Also with flash we can have interactive flash side show and banners. Another benefit of using flash image slide show is we can have text added to the animation.
In this flash tutorial we will learn how to create a basic image slide show in flash action script 3, and the type of applications that can be made by using flash image slide shows and few types of flash slideshows.
In future I plan to write a flash component for Image Slide show. I have attached the flash example and source code with the article you can download it at the link at the end of the article.
There are number of flash slide show or presentation creation software available online. They make life complex. In reality it is quite easy to make you own flash animation.
If you are looking for a customize flash animation, image slide show or any flash application you may contact mbilal@imaginationdev.com
I will be glad to help you out. If you need any advice you may post comments under this article.
There are number of types of flash animation that can be used in creating flash slide shows or animations.
- Flash 3d Slide Show (slideshow)
- Flash Presentation Slide Show (slideshow)
- Flash Banners Slide Show (slideshow)
- Flash Image Galleries Slide Shows (slideshow)
- Flash Text Slide Shows (slideshow)
- Flash Interactive Slide Shows (slideshow)
- Flash Image Slide Shows with Effects
There are 2 basic styles to make flash image slide shows. Namely dynamic image or picture slide show and static image or picture slide show.
Static flash picture slide show usually consists of some images that are internal to the flash and are embedded in the swf files. They have a benefit that there can be various customized animations that we can have in static image slide shows. The problem is they lack in security. There are numbers of flash de-compilers available which can extract the images and other people might use them.
If you want to have more security in terms of image copy rights its always better to use dynamic image or picture slideshow. Dynamic image slideshow are developed by loading external images at run time through XML.
In my flash picture slideshow tutorial I have used the dynamic approach also in flash action script 3 now its really easy to control animation and transition effects through tween classes.
Also by loading external we have a benefit that we can use flash xml image slideshow as a flash random image slideshow.
Here Goes the code for the Loading and Display and Tweening. I have also attached the source code along with all files at the end of the article.
////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////
import fl.transitions.*;
import fl.transitions.easing.*;
////////////////////////////////////////////////////////////////////////
// Variables Initiation and Declaration
////////////////////////////////////////////////////////////////////////
var pic_prev_mc:MovieClip=new MovieClip();
var pic_mc:MovieClip=new MovieClip();
var picInitial_mc:MovieClip=new MovieClip();
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML;
var thumbLoader:Loader;
var index:int=0;
var picArray:Array=new Array();
var timer :Timer=new Timer(1000,4);
var curr:int=1;
var totalPictures:int;
var flag:int=0;
var bitmap:DisplayObject;
var effect:Object=Photo;
////////////////////////////////////////////////////////////////////////
// Function XMl Loading
////////////////////////////////////////////////////////////////////////
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
var httpHeader : URLRequestHeader = new URLRequestHeader("pragma","no-cache");
var path:String="Banner.xml";
xmlLoader.load(new URLRequest(path));
function LoadXML(e:Event):void {
xmlData = new XML(e.target.data);
stage.scaleMode = StageScaleMode.EXACT_FIT;
stage.stageWidth= xmlData.Width;
stage.stageHeight=xmlData.Height;
getValues(xmlData);
}// end of Load XML
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR,funcError);
function funcError(event:IOErrorEvent){
trace("Error occured in XML Loading");
}
function getValues(input:XML) {
var xmlCategoryList:XMLList = input.children();
totalPictures=input.children().length();
var item:XML;
for each (item in xmlCategoryList) {
loadThumbs();
}
}
////////////////////////////////////////////////////////////////////////
// Function loadThumbs
////////////////////////////////////////////////////////////////////////
function loadThumbs():void {
thumbLoader = new Loader();
thumbLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadThumbProgress);
thumbLoader.contentLoaderInfo.addEventListener(Event.INIT, thumbLoaded);
thumbLoader.load(new URLRequest(String(xmlData.path[index])));//access the thumbnails
function loadThumbProgress(e:ProgressEvent):void {
}
////////////////////////////////////////////////////////////////////////
// Function thumbloaded
////////////////////////////////////////////////////////////////////////
function thumbLoaded(e:Event):void {
for(var i:int=0;i<totalPictures;i++){;
picArray[i]=xmlData.path[i];
}
addChild(picInitial_mc);
picInitial_mc.addChild(thumbLoader.content);
bitmap=thumbLoader.content;
}
function xmlLoadFail(event:IOErrorEvent):void {
trace("error loading the XML");
}
}
////////////////////////////////////////////////////////////////////////
// Function Next Pic Loading
////////////////////////////////////////////////////////////////////////
function nextPicLoad(string:String) {
thumbLoader = new Loader();
thumbLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadThumbProgress);
thumbLoader.contentLoaderInfo.addEventListener(Event.INIT, thumbLoaded);
thumbLoader.load(new URLRequest(String(string)));
function thumbLoaded(e:Event):void {
stage.addChild(thumbLoader.content);
addChild(pic_mc);
addChild(thumbLoader.content);
pic_mc.addChild(thumbLoader.content);
bitmap=thumbLoader.content;
//Blinds, Fade, Iris, Photo, PixelDissolve, Rotate, Squeeze, Wipe, or Zoom.
TransitionManager.start(pic_mc, {type:Fade, direction:Transition.IN, duration:1, easing:Regular.easeInOut});
TransitionManager.start(pic_mc, {type:Wipe, direction:Transition.IN, duration:1, easing:Regular.easeIn});
}
function loadThumbProgress(e:ProgressEvent):void {
}
}
////////////////////////////////////////////////////////////////////////
// Function Pic Display
////////////////////////////////////////////////////////////////////////
function picDisplay() {
timer.start();
timer.addEventListener(TimerEvent.TIMER_COMPLETE,funcTimer);
function funcTimer(event:TimerEvent) {
for(var k:int=0;k<pic_mc.numChildren;k++){
pic_mc.removeChildAt(k);
}
if (flag==0) {
flag=1;
removeChild(picInitial_mc);
} else {
removeChild(pic_mc);
}
addChild(bitmap)
nextPicLoad(picArray[curr]);
curr++;
if (curr==totalPictures) {
curr=0;
}
timer.reset();
timer.start();
}
}
picDisplay();
stop();
I have attached the code for free flash image slideshow. you are free to use and modify the code the way you like.
Kindly Let me know about your remarks if this article is being helpful in solving your problem.
Download Sample Project : Image Slide Show Source Code
A running sample can be viewed at the following link
http://actionscript-blog.imaginationdev.com/samples/banner-slideshow/Banner.swf
Flip Horizontal Vertical Display Object MovieClip Flash Action Script
Hi, Today i came across a problem while using code from snipplr article for Flipping Display Objects and MovieClip in Flash Action Script 3. Problem was i was using a button to flip the movieclip horizontal and vertical. If i clicked the button twice it use to change its location. I have tweak the code to check if the movie clip is already mirrored or flipped horizontal or vertically and inverse the previous effect.
Flipping or Mirror Movie Clip and display object is a common requirement these days. Flash action script 3 geom.matrix class has solved most of the problems. Though its a bit tricky to use them. Any further questions let me know. Thank you all for supporting the blog.
Here Goes the code to flip Mirror action script 3 display objects and movie clips
function flipHorizontal(dsp:DisplayObject):void
{
var matrix:Matrix = dsp.transform.matrix;
matrix.transformPoint(new Point(dsp.width/2,dsp.height/2));
if(matrix.a>0){
matrix.a=-1*matrix.a;
matrix.tx=dsp.width+dsp.x;
}
else
{
matrix.a=-1*matrix.a;
matrix.tx=dsp.x-dsp.width;
}
dsp.transform.matrix=matrix;
}
function flipVertical(dsp:DisplayObject):void
{
var matrix:Matrix = dsp.transform.matrix;
matrix.transformPoint(new Point(dsp.width/2,dsp.height/2));
if(matrix.d>0){
matrix.d=-1*matrix.d;
matrix.ty=dsp.y+dsp.height;
}
else
{
matrix.d=-1*matrix.d;
matrix.ty=dsp.y-dsp.height;
}
dsp.transform.matrix=matrix;
}
Load External Image and SWF Flash Action Script 3
Hi, every one here goes another article. I will sure come up with flash action script 3 MP3 player Part 2 soon. Let us focus on loading external images in flash action script 3. For the beginners its a huge problem to load external images and swf file into a flash Movie clip and and flash action script 3. Some time people consider it hard to attach a pre loader on the loading external image in flash action script 3. I was working on an flash image gallery project and came across the same problem. What i was planning to have a flash action script 3 class to do my external image loading. I thought of an idea to make this class a reusable utility to load external image in flash action script 3 and built in support for a preloader. I have defined a class named ImageContainer. Image Container class is inherited from MovieClip class. This class support dynamic loading of external image and swf file into flash. In the attached sample i have loaded a JPEG file and a SWF file dynamically into flash.
Here goes the code for the Image Container class.
package image{
import flash.display.MovieClip;
import flash.events.ProgressEvent;
import flash.events.Event;
import flash.display.Loader;
import flash.net.URLRequest;
import fl.transitions.*;
import fl.transitions.easing.*;
public class imageContainer extends MovieClip {
public var imageURL:String;
public var urlRequest:URLRequest;
public var imageLoader:Loader;
public var imageWidth:Number;
public var imageHeight:Number;
public var preLoader:Loader;
var mcImage:MovieClip=new MovieClip();
public function imageContainer(Imagewidth:Number,Imageheight:Number,url:String,path:String) {
preLoader=new Loader();
preLoader.load(new URLRequest(path));
preLoader.scaleX=2;
preLoader.scaleY=2;
preLoader.x=Imagewidth/2-preLoader.width/2;
preLoader.y=Imageheight/2-preLoader.height/2;
addChild(preLoader);
imageURL=url;
imageWidth=Imagewidth;
imageHeight=Imageheight;
loadThumb(url);
}
public function loadThumb(url:String) {
urlRequest=new URLRequest(url);
imageLoader=new Loader();
imageLoader.load(urlRequest);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,funcComplete);
function funcComplete(e:Event) {
removeChild(preLoader);
trace("Successfully Loaded");
imageLoader.content.width=imageWidth;
imageLoader.content.height=imageHeight;
mcImage.addChild(imageLoader.content);
TransitionManager.start(mcImage,{type:Fade, direction:Transition.IN, duration:3, easing:Regular.easeIn});
addChild(mcImage);
}
}
}
}
I have applied transition effect after loading of external image is completed. This class will help you save time in loading external images and applying pre loader to Flash action script 3.
Here goes the code for Using the Image Container class.
import image.imageContainer;
//Loading SWF
var im:imageContainer=new imageContainer(200,200,"001.swf","loader.swf");
addChild(im)
//Loading Image
var im1:imageContainer=new imageContainer(200,200,"Sunset.jpg","loader.swf");
var child = addChild(im1)
child.x = 300;
Kindly Let me know about your remarks if this article is being helpful in solving your problem.
Download Sample Project : Load Image Source Code
A running sample can be viewed at the following link
www.imaginationdev.com/actionscript-blog/samples/LoadImage/LoadImage.swf
Vote For New Action Script 3 Article and Tutorial
Hi, Every one due to some time constraints i am unable to post articles all at a time, as i have a lot of articles and samples in my mind . I am listing down the articles. I would ask for votes which article to write first
funny but i guess its a good way to communicate
1- FLV player using flash action script 3
2- Flash MP3 player Part 2
3- Flash Drawing Board Sample
4- Flash Communication With C#
5- Flash Communication With PHP
6- Flash Communication With JAVA Sockets Programming
7- Flash communication with VB.net
8- Generating PDF using flash and C#
9- Flash communication with Java script.
10- flash xml action script 3 image gallery
11- flash component development basics
This is what all in my mind if you have others in MIND . Also I might add article for flash media server.
If you have any idea in mind, or any solution that you want to share you are well come. Also If you have any thing you need to ask or need help you may leave comments. I will definitely reply Back.
Article with maximum votes will be Written on priority basis.
Thanks All
Action Script 3 MovieClip MouseEvent CLICK Problem
Hi, All Thank you Guys for Supporting my articles. Today i came across a very strange behaviour of flash action script 3 click MouseEvent.
I had a custom class lets say
Public class CustomMovieClip extends MovieClip {
public function CustomMovieClip()
{
addChild(new DisplayObject()); //Suppose its name is instance123
}
}
Now after that if i add a reference of this class on Lets suppose stage
var mc = stage.addChild(new CustomMovieClip());
mc.addEventListener(MouseEvent.Click,clicker);
trace(mc.name);
//Suppose its name assigned is instance124
function clicker(event:MouseEvent)
{
trace(evt.target.name); //Here it will out put instance123,
//instead of instance124
}
You see i have applied event handler on the object of CustomMovieClip but its fired for the child. Here if i need to Get the state of the CustomMovieClip object i need to change the following
function clicker(event:MouseEvent)
{
trace(evt.target.parent.name); //Here it will out put instance124,
//now its the right out put
}
if you have found this posting help full and if you have further explanation to why this happens Kindly share it with all here.
Do write comments, this will help me motivated to right more and more articles on Action script 3.
Flash Action Script 3 MP3 Player Part 1
Here goes Flash Action Script 3 MP3 Player - Part 1. Need Your comments and support on the articles.
I am writing this first version of Flash Action Script 3 MP3 for beginners so that they can have an idea of Flash Action Script 3 Sound Classes. Also this code uses memory optimization techniques to reduce memory leaks.
To Learn More About Memory Optimization read my previous post
http://actionscript-blog.imaginationdev.com/Memory-Optimization-Flash-Action-Script-3
Flash Action Script 3 MP3 Player can be developed in 2 ways. 1- Songs are played once they are completely downloaded on the local machine, Part 1 of my Flash Action Script 3 MP3 Player uses this techniques. this approach is suitable when developing a desktop application. 2- Songs are buffered and streamed from the server and played simultaneously. This type of approach is common for Online Flash Action Script 3 MP3 Player. Part 2 of this article series will cover the 2nd methodology.
Building a Flash Action Script 3 MP3 Player is really easy using Flash Action Script 3 classes. Once you have the concepts of Sound class, SoundChannel class and Timer class in Flash Action Script 3 you are ready to develop a Media Player in Flash Action Script 3. In case you need guidance and help in the above mentioned classes you are welcome to leave comments and i will respond as soon as possible.
This might not be the best Flash Action Script 3 MP3 Player. This sure will guide you how to develop a Flash Action Script 3 MP3 Player using flash action script. There are number of flash media players available on the internet but very few i saw focussed on the fact that action script sound class has some problems when optimizing memory space. So i thought to write one sample of my own.
This flash MP3 player is easily customizable and reusable. In coming future i plan to write a Flash MP3 Player Component using Action Script3. Hopefully that article will also cover the basis of creating a flash component.
You can use the flash action script 3 Mp3 player code to build your own customized Flash Action Script 3 MP3 Players. Basic idea will always remain the same.
Flash Action Script 3 MP3 Player development starts with the code for loading XML and inserting data in the play list.
/////////////////////////////////////////////////////////////////
//Loading XML
/////////////////////////////////////////////////////////////////
var xmlData:XML; var xmlLoader:URLLoader = new URLLoader();xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("playlist.xml"));
function LoadXML(e:Event):void {
trace(LoadXML); xmlData = new XML(e.target.data);
function getValues(input:XML) {
var xmlCategoryList:XMLList = input.children(); var item:XML;var intCount:int = 0;
for each (item in xmlCategoryList) {
playList.addItem({label:item.title, data:item.url}); intCount = intCount + 1;
}
}//end of get Values Function
getValues(xmlData);
}// end of Load XML
After that we will wait until user clicks on any song in play list. For handling play list event we will write the following code.
playList.addEventListener(Event.CHANGE, playListChangeHandler);
function playListChangeHandler(event:Event) {
if (flagSoundChannel==1) {
soundChannel.stop();
} else if (flagSoundChannel==0) {
flagSoundChannel=1;
}
playSound(event.target.selectedItem.data);timeSlider.value=0;
}// end of change Handler
Above code calls another important function playSound. This method loads the new sound in the sound Object.
function playSound(path) {
songPath.url = path;
if(playerObject.sound!=null)
delete playerObject.sound;
playerObject.sound = new Sound();
addSoundEvents();
playerObject.sound.load(songPath);
}
Above code requires sound events to be handled before a new sound object is created. If you focus on the delete playerObject.sound; statement, this deletes the previous allocation of memory for the sound object. If we don’t do this a lot of memory will leak and eventually application will crash.
/////////////////////////////////////////////////////////////////
//Sound Loading Event Handler Function
/////////////////////////////////////////////////////////////////
function addSoundEvents():void
{
playerObject.sound.addEventListener(Event.COMPLETE, funcSoundLoaded);
playerObject.sound.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
playerObject.sound.addEventListener(ProgressEvent.PROGRESS,funcOnLoadProgress);
}
function funcSoundLoaded(event:Event) {
var soundObject:Sound = event.target as Sound;
var totalSoundDuration:Number;
soundChannel=soundObject.play();
totalSoundDuration=(soundObject.length/1000)/(60);
totalSoundDuration=Math.floor((totalSoundDuration*100));
totalSoundDuration=totalSoundDuration/100;
timeSlider.maximum=(soundObject.length/1000);
sliderDivisionValue=totalSoundDuration;
fileTimeInSec = Math.floor(playerObject.sound.length/1000);
secTimer.start();
}//end of Function Loaded
function funcOnLoadProgress(event:ProgressEvent):void {
var loadedPct:uint =Math.round(100 * (event.bytesLoaded / event.bytesTotal));
trace("The playerObject.sound is " + loadedPct + "% loaded.");
}
function onIOError(e:IOErrorEvent) {
trace("The playerObject.sound can not be Loaded"+ e.text);
}
Above is code implementation of sound event handlers. Lastly we will add Timers and GUI element event handlers.
/////////////////////////////////////////////////////////////////
//Control Handlers UIDesign
/////////////////////////////////////////////////////////////////
btnStop.addEventListener(MouseEvent.CLICK,funcStop);
btnPause.addEventListener(MouseEvent.CLICK,funcPause);
btnPlay.addEventListener(MouseEvent.CLICK,funcPlay);
btnForward.addEventListener(MouseEvent.CLICK,funcForward);
btnBack.addEventListener(MouseEvent.CLICK,funcReverse);
soundChannel.addEventListener(Event.SOUND_COMPLETE, funcComplete);
function funcComplete(event:Event) {
soundChannel.stop();
timeSlider.value=0;
currPosition=0;
}
function funcStop(event:Event) {
secTimer.reset();
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
function funcPause(event:Event) {
secTimer.stop();
currPosition= soundChannel.position;
soundChannel.stop();
btnPlay.visible=true;
btnPause.visible=false;
}
function funcPlay(event:Event) {
soundChannel.stop();
soundChannel=playerObject.sound.play(currPosition);
btnPlay.visible=false;
btnPause.visible=true;
secTimer.start();
}
function funcForward(event:Event) {
if (soundChannel.position+forwardDuration<=playerObject.sound.bytesTotal) {
timeSlider.value+=forwardDuration/1000;
soundChannel.stop();
soundChannel=playerObject.sound.play(soundChannel.position+forwardDuration);
}
else
{
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
}
function funcReverse(event:Event) {
if (soundChannel.position-forwardDuration>0) {
timeSlider.value-=forwardDuration/1000;
soundChannel.stop();
soundChannel=playerObject.sound.play(soundChannel.position-forwardDuration);
}
else
{
timeSlider.value=0;
currPosition=0;
soundChannel.stop();
flagSoundChannel=0;
}
}
/////////////////////////////////////////////////////////////////
//Control Handlers Sliders
/////////////////////////////////////////////////////////////////
timeSlider.addEventListener(SliderEvent.THUMB_PRESS,sliderPressed);
timeSlider.addEventListener(SliderEvent.THUMB_RELEASE,sliderReleased);
timeSlider.addEventListener(SliderEvent.CHANGE,sliderChangeHandler);
timeSlider.liveDragging =true;
function sliderChangeHandler(event:SliderEvent) {
secTimer.stop();
soundChannel.stop();
soundChannel=playerObject.sound.play(event.target.value*1000);
secTimer.start();
}
function sliderPressed(event:SliderEvent) {
}
function sliderReleased(event:SliderEvent) {
secTimer.stop();
soundChannel.stop();
soundChannel=playerObject.sound.play(event.target.value*1000);
secTimer.start();
}
/////////////////////////////////////////////////////////////////
//Control Handlers Timers
/////////////////////////////////////////////////////////////////
secTimer.addEventListener(TimerEvent.TIMER, onTick);
secTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
function onTick(event:TimerEvent):void {
trace("Timer is running");
timeSlider.value+=1;
}
function onTimerComplete(event:TimerEvent):void {
trace("Time's Up!");
}
For Further details on voice control and sound buffering you may contact me. I will soon be writing part 2 of the flash MP3 Player series with voice control and Sound Buffering.
Kindly Let me know about your remarks if this article is being helpful in solving your problem.
Download Sample Project : Flash MP3 Player Using Action Script 3
A running sample can be viewed at the following link
www.imaginationdev.com/actionscript-blog/samples/mp3-player/play.html
Memory Optimization Flash Action Script 3
Hi, Every one here is another important article. Which i see really few have discussed, thats is memory optimization in Flash Action Script 3. After all improvements still garbage collection is a bit slower i think. Or I guess there is no garbage collection. For example if i declare var sound:Sound=new Sound(); now if i use new keyword to allocate memory. There is no way to de-allocate memory. Now if i call following line sound=new Sound(); This will cause a new memory to be allocated to the Sound Object and the old memory refrence will be lost but memmory will reside untill the end of applicatio. Now consider a Flash Media Player with a play list and each time a Sound object is Allocated new memory, than you can imagine the memory leak. Its strange there is no way to deallocate a memory after it is allocated by "new" keyword. Although there is delete keyword in flash actionscript 3. For example if i write delete sound; This statement will give Error that "1189: Attempt to delete the fixed property sound. Only dynamically defined properties can be deleted." Now sound object although it is dynamically created but it can’t be destroyed. Solution that i found is to create an ParentObject of object class and than create the sound object as a dynamic property of ParentObject. 1- Declare parent object var playerObject:Object = new Object(); 2- Create the sound object as dynamic property of this object. playerObject.sound = new Sound(); 3- Delete the memory allocated at the end delete playerObject.sound; This time delete case will deallocate memory allocated to the dynamic property "playerObject.sound" This strategy can be used any where, to avoid the memory leaks in flash actionscript 3 applications. I have used the Sound object example as i am now working on an article for the Flash MP3 Player. And i came across this problem during its development. For Questions You can post your feed back I would appreciate your comments. Your support will encourage me to post more and more aricles. If you are looking for live assistance on any projects you are well come. I plan to start an Action Script 3 training course for beginners. Those of you intrested may contact.
Save JPG JPEG PNG BMP Image Action Script 3
Well finally i got time to Bring together a sample project. Kindly Let me know about your comments if this article is being helpful in solving your problem.
Kindly do write your comments on this post. This will encourage me to write more and more articles for action script community.
I have recently been working on an online Drawing Board application. We needed to save the flash movie as an Image in JPEGEncoder, PNGEncoder and BMPEncoder. I searched internet i got a lot of help but it was all dispersed on multiple site also i needed to save the JPEG, PNG, BMP in 300 dpi through flash action script. On the internet i found 2 ways to save the flash movie to any Image format such as JPEG, PNG, BMP.
1- Use the BitmapData class in action script 2/3 and get the data in string format that is basically value of each pixel and send the data 2 PHP file on the server. PHP file would prepare the header of the required image format and save the JPEG, PNG, BMP on the server as well and than at last when JPEG, PNG, BMP is saved than prompt user to download JPEG, PNG, BMP on their PC. This method had a major flaw that when data was very large in case of Bitmap image this method becomes really slow and some time script gives error on the browser.
Such Kind of solution is available on the following link http://www.quasimondo.com/archives/000645.php
Also i have attached the files that i downloaded from that website for the ease. The problem was i had to change DPI but PHP code was not that understandable. This solution is recommendable when using action script 2, as action script 2 does not have that much support for images.
2- Now for action script 3, Ah i love Action script 3 as always coming to rescue. I found classes written in Action Script 3. I have forgot the direct links from where i downloaded those files (As there were multiple locations). In this solution all the code is in flash action script.
There are 4 major classes BitmapData, JPEGEncoder, PNGEncoder and BMPEncoder. These classes prepare the header and every thing in action script and Post the Bytes as Array to PHP webpage. Now from here there are 2 ways One is PHP just temporary save file and prompt user to save or open the file. This had problems when a flash page was called from Actions script a new window in the browser open but if there is a Pop up blocker than no save dialog use to appear, as the page that was called the Popup blocker blocks it. The solution to solve this problem is use the “_self” parameter instead of “_blank”. This again had problem with internet explorer 6, but worked well with explorer 7 and Firefox. Problem was the the session expired on IE 6 once the JPEG, PNG, BMP image is saved on the server. This cause the save method just to run once on the browser instance than every time to make it work we needed to refresh browser and that was not acceptable in our solution.
Other way around is that, save the file on the server and i used a Timer in Action script which will continuously check as the file is completely saved on the server. If file is completely saved on the server than flash Call the download function of the FileRefrence class. This function downloads the file on user desktop. Now there is our choice weather to delete the file from server or to keep it on the server as well. This method is excellent as no browser or pop up blocker problem.
I have made changes in the following classes: JPEGEncoder, PNGEncoder and BMPEncoder. I have commented the section for the DPI settings in the classes you may look at the classes provided.
To use Above files make changes in the package declaration. To adjust to your older’s hierarchy.
Following is the code Accessing the above classes and Using the FileReference class to download the file on personal computer.
<pre>
////////////////////////////////////////////////////////////////////////////
//Imports
flash.display.Stage;
import flash.display.Sprite;
import flash.display.MovieClip;
import com.adobe.images.JPGEncoder;
import com.adobe.images.BMPEncoder;
import flash.net.navigateToURL;
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
////////////////////////////////////////////////////////////////////////////
//Initialization
var serverUniqueFileName:String;
mcSavingMsg.visible=false;
//Need to change the name to your sepcified server
var serverPath:String = "./";
//var serverPath:String = "http://localhost/";
var timer:Timer;
var isDownloadProgress = false;
////////////////////////////////////////////////////////////////////////////
// Call this function On Button Save
////////////////////////////////////////////////////////////////////////////
btnSave.addEventListener(MouseEvent.CLICK, clickHandlerBtnSave);
function clickHandlerBtnSave(e:Event)
{
serverUniqueFileName=getUniqueFileName("Snapshot");
if(comboFileFormat.selectedItem.label == ".jpg")
{
createJPG(mcBg, 85, serverUniqueFileName+".jpg");
}
else
{
createBmp(mcBg,serverUniqueFileName+".bmp");
}
//Similarly Save PNG could be added into the system
}
function timerHandler(event:TimerEvent)
{
}
function timerCompleteHandler(event:Event)
{
isDownloadProgress=false;
}
var downloadURL:URLRequest;
var file:FileReference;
//////////////////////////////////////////////////////////////////////////////////////////////////////
function FileReference_download()
{
trace("file to download "+serverPath+serverUniqueFileName);
downloadURL = new URLRequest();
downloadURL.url = serverPath+serverUniqueFileName;
file = new FileReference();
configureListeners(file);
file.download(downloadURL, serverUniqueFileName+comboFileFormat.selectedItem.label);
}
function configureListeners(dispatcher:IEventDispatcher)
{
dispatcher.addEventListener(Event.SELECT, selectHandler);
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
}
function getUniqueFileName(fileName:String):String
{
var date:Date = new Date();
return fileName+date.getTime();
}
function completeHandler(event:Event):void
{
mcSavingMsg.visible=false;
deleteDownLoadFile(serverUniqueFileName);
}
function selectHandler(event:Event):void {
var file:FileReference = FileReference(event.target);
trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
}
//After file is downloaded on Desktop Call this function to delete file from the server
function deleteDownLoadFile(fileName:String)
{
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest (serverPath+"jpg_encoder_download.php?delname=" + fileName);
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
var jpgURLLoader:URLLoader = new URLLoader();
jpgURLLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
jpgURLLoader.addEventListener( Event.COMPLETE, deleteTempServerFile );
jpgURLLoader.addEventListener( IOErrorEvent.IO_ERROR, sendIOErrorDeleteFile );
function deleteTempServerFile(evt:Event)
{
var write = evt.target.data.write;
trace ('DeleteFileWrite ' + write);
}
function sendIOErrorDeleteFile(event:Event)
{
}
jpgURLLoader.load( jpgURLRequest );
}
//Fired when URL Loading Complete
function imageUrlLoaderComplete(evt:Event)
{
var write = evt.target.data.write;
if(write=="yes")
FileReference_download();
}
function sendIOError(event:Event)
{
trace("Error occured");
}
////////////////////////////////////////////////////////////////////////////////////
// Creating JPG Image
////////////////////////////////////////////////////////////////////////////////////
function createJPG(m:MovieClip, q:Number, fileName:String="snapshot.jpg")
{
serverUniqueFileName=fileName;
var jpgSource:BitmapData = new BitmapData (m.width, m.height);
jpgSource.draw(m);
var jpgEncoder:JPGEncoder = new JPGEncoder(q);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest (serverPath+"jpg_encoder_download.php?name=" + fileName);
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = jpgStream;
var jpgURLLoader:URLLoader = new URLLoader();
jpgURLLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
jpgURLLoader.addEventListener( Event.COMPLETE, imageUrlLoaderComplete );
jpgURLLoader.addEventListener( IOErrorEvent.IO_ERROR, sendIOError );
jpgURLLoader.load( jpgURLRequest );
}
/////////////////////////////////////////////////////////////////////////////////////////
//Creating bitmap images
/////////////////////////////////////////////////////////////////////////////////////////
function createBmp(m:MovieClip,fileName:String="snapshot.bmp")
{
serverUniqueFileName=fileName;
var bmpSource:BitmapData = new BitmapData (m.width, m.height);
bmpSource.draw(m);
var bmpStream:ByteArray = BMPEncoder.encode(bmpSource);
var header:URLRequestHeader = new URLRequestHeader ("Content-type", "application/octet-stream");
var bmpURLRequest:URLRequest = new URLRequest (serverPath+"jpg_encoder_download.php?name=" + fileName);
bmpURLRequest.requestHeaders.push(header);
bmpURLRequest.method = URLRequestMethod.POST;
bmpURLRequest.data = bmpStream;
var bmpURLLoader:URLLoader = new URLLoader();
bmpURLLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
bmpURLLoader.addEventListener( Event.COMPLETE, imageUrlLoaderComplete );
bmpURLLoader.addEventListener( IOErrorEvent.IO_ERROR, sendIOError );
bmpURLLoader.load( bmpURLRequest );
}</pre>
Here Server Path will be your server location where your files reside.
PHP File to save the image on the server can be downloaded here. PHP File Version 2
For Further details on saving file through FileRefrence class you may contact me if you get stuck some where.
Well finally i got time to Bring together a sample project. Kindly Let me know about your remarks if this article is being helpful in solving your problem.
Download Sample Project : Saving Image Actionscript 3 + PHP
A running sample can be viewed at the following link
www.imaginationdev.com/actionscript-blog/samples/save-image/SaveImage.swf
