This is an update to my earlier post where I demonstrated how to dynamically generate an image of a DisplayObject in Flash and push it up to the server using PHP. I’ve cleaned up and extended the code here to now allow you to also save an image to the desktop using the new save( ) method of the FileReference class introduced in Flash Player 10.
To use this class download the source files and create a new BitmapSnapshot object passing in the DisplayObject you want to create an image of as well as an optional file name, width and height. If width and height are omitted BitmapSnapshot will use the full width and height of the object you are passing in.
Note : BitmapSnapshot will generate a jpg or a png based on the extension of the filename you pass in.
The default output will be a png because it’s encoding algorithm is much faster than that of jpeg’s.
private function saveToDesktop():void { var img.BitmapSnapshot = new BitmapSnapshot(_canvas, _filename); img.saveToDesktop(); } private function saveOnServer():void { var img:BitmapSnapshot = new BitmapSnapshot(_canvas, _filename); img.saveOnServer(_phpscript, _destination); }
A note on dependencies : BitmapSnapshot does rely on the fantastic jpeg and png encoder classes written by Tinic Uro as part of the AS3CoreLibrary. These files are included in the ‘libs’ directory along with BitmapSnapshot so be sure this folder is in your class path when you go to compile.
To see the generated image saved to the server, be sure to clear your cache and view the image here.
As always please leave any questions or problems in the comments below.







48 Responses to Dynamically Create an Image in Flash and Save it to the Desktop or Server
Excellent tutorial. This is by far the best tutorial on saving to a sever, I’ve found. Keep up the great work.
Where did you get BitmapSnapshot class can’t see how to import it?
Excellent tutorial. Great information. For the save on server…I get the “FILE UPLOAD FAILED” error. I could use your assistance in helping me to understand what I need to think and do to render a working version…Look forward to your response. Have an amazing day and Thank you! Lisa
Ensure you have write permissions on the server directory you are attempting to save to otherwise this will fail.
Yes, write permissions are good. I sent you an email at your @quietless.com. Do you think you may have time to respond there? I appreciate your response…Thank you, Lisa
There are a near infinite number of reasons why your attempt to save to server may be failing.
Some things to consider:
1. Ensure you have write permissions on the target server directory (chmod 777)
2. Ensure the path to the php script (upload.php) on your server is correct.
3. Ensure you’re not trying to save the image before Flash has created it from your target MovieClip.
4. Use an HTTP sniffer like Charles, Firebug or the activity monitor in Safari to check what is being sent to your server.
This is really cool – I am trying to develop a drawing app that can save images.
How did you get those circles to redraw in real time? It that just a particle effect?
I am trying to make it so that the user can replay the drawing as well. So if they draw a smiley face, they can see it redrawn after they have finished.
any thoughts?
@jordan. I’m just attaching a few hundred circles to the screen inside of a for loop and placing them on the stage at random x & y positions. Look at the draw function inside Canvas.as. As for recording the screen you could try making a copy of the graphics object you are drawing into and then pushing that copy into an array on some timer event or enterframe handler. Then iterate over that array to redraw your animation on playback. This can get expensive in terms of memory fast but it is just one approach off the top of my head.
Hi Stephen, Thank you for your help. Where exactly do I pass in a new width and height? Have a great Day! Lisa
Hi,
I want to take snapshot of movie clip..There may be some objects will be placed on top of movie clip..Still that snapshot should capture anything on that movie clip..
Actually write a code to save a movie clip as image which saves contents(only childs of movie clip) of movie clip.. But i want it to save as anything has seen on movie clip must be saved as image..
Do u have any pointers regarding that?
Thanks in advance,
syaam
Hey!
First i have to say – Thanks a lot for sharing this info!
But as a beginner in flash – and as a person that is in need of this kind of info – this tutorial is just too advanced for me to understand!
Can you please record the procedure for using this class? What i’m struggling with is what to change and what to not change….
You can use this great and free software to record the steps: http://camstudio.org/ – You don’t really need to record any audio!
You can use those settings in camstudio for best quality…: http://www.youtube.com/watch?v=jnxadwJWY2M
It’ll be really great if you can record the procedure, I’m very sure that many beginners in Flash wil be happy!
Hi Stephen, great tutorial but, why files do not include the fla? how can I compile it?
Thanks
ok, I realize that it is a flex project!! ^^
Hi, I was looking for something like this.
But I have a problem. By the looks of things averything goes great, I even get ‘Upload of image.png was successful’, but when I look at the folder the image is supposed to be in, there is nothing there. I’ve tried delaying image upload from the point when the snapshot is been taken, but no result.
What could be the problem?
Oh, I forgot to mention. This is for save to server.
When instead of saving to the server I try saving on my computer everything goes well and the image is there.
1. Ensure you have write permission on the destination folder.
2. Ensure you are running php5, otherwise part of the server script will fail.
Three questions:
1) Is there a way to keep the transparency of the image while saving the image to the server?
2) Is there a way to have a lower quality version for a lower filesize? (for instance, a setting of 10 would be highest quality with most filesize saved, and a setting of 1 would be lowest quality with lowest filesize saved, get what I mean?)
3) Is there a way to save as .gif? This is not as important however as the other two. The other two are a must for me.
If you can help me with this, please let me know.. you can contact me at my site at http://www.theothersun.com or at the email I entered into the comment. Thanks!
By default BitmapSnapshot writes to a png which supports transparency. You can also write to a jpeg by passing in “MyImage.jpg” as the second argument in the constructor. Inside the BitmapSnapshot class you can set the jpg compression to anything you want. It defaults to 80%. Gif’s are not supported.
Dear Stephen,
The jpg compression line is here in the BitmapSnapshot class?
if (ext==’jpg’) _image = new JPGEncoder(80).encode(bmd);
I saw a line for png as well :
if (ext==’png’) _image = PNGEncoder.encode(bmd);
Is there any compression for PNG?
I tried saving a PNG transparent.. Ill upload an image with transparencies which show up fine in Flash, then when saving, the transparency has been replaced with white. Does this have something to do with the mask? What does the mask serve for by the way that is passed as an argument when saving the image?
I also checked whether the image’s bitmapData is transparent: trace(“transparent: “, image.bitmapData.transparent);
Whenever I uploaded a .gif or .png, it came up as true, and .jpg came up as false, as expect. So when I bring .png images that are transparent into flash, the parts that are transparent still show up transparent in flash, but when saving it as PNG it comes up with a white background instead of the transparent areas. Any help on that , if you are aware of what could be the cause? Thanks!
Any reply to the last comment / help ? =)
Any one have this working with flash player 10.2? i think adobe might have broken it
This is not working, BitString doesn’t exist anymore. Any alternative solution?
hi, thank u so much for for this usefull class.
I m wondering how to catch the “complete” event, that i could load generated image once its creation complete.
maybe u could help on this
You’re so awesome! I do not suppose Ive learn anything such as this previously. So interesting to search out person with several initial ideas on this particular subject. realy thanks just for starting this up. this page is something is helpful on the internet, anyone with a little creativity. beneficial position for bringing something which new to the internet!
Hey, This tutorial seems like something I’m after but I can’t understand how to use it.
I’m trying to use your BitmapSnapshot and saveToDesktop. In my project, I upload an image to my server which then displays in my Swf in a MovieClip. Can I use your BitmapSnapshot and saveToDesktop?
Sorry, I’m a bit of a noob at this stuff… xD
The MovieClip in question is called “img_mc”, which I guess is my DisplayObject.
Hi I am not a flash programmer just a person who gets things done I was wondering if you have the actual flash file I could look at to try and work backwards. I simply need to be able to save a simple jpeg or png.
Thank you
I seem to be missing a file to get this to work as flash throws up this error to me.
1046: Type was not found or was not a compile-time constant: BitString.
the full error im getting is actually
JPGEncoder.as, Line239 1046: Type was not found or was not a compile-time constant: BitString.
which is a function definition on line 239 this is the code snippet in question > private function writeBits(bs:BitString):void{
what am I doing wrong ? or where is the class definition for BitString..
Apologies to you guys, the .zip was missing the BitString class as a few of you have pointed out. I just updated the package with the missing file and added a .fla file so you should be able to just unpack the .zip, compile the .fla and have everything work. Continue to post comments here if you run into problems.
Props m8, Great stuff here and very well done. What I learned here will be Very valuable indeed.
I have run into another issue and Similar to a few other posts.
This issue is with transparency’s when saving out as a png.
No matter how I set up my _canvas, it wants to add the flash stage color as the Background color to the image saved out.
Any advice on this would be greatly appreciated.
And Thanks again !!
Has anyone figured out how to get the balls to have a transparent background when saved out as a png?
TRANSPARENCY FIX:
in BitmapSnapshot.as, change
var bmd:BitmapData = new BitmapData($width || $targ.width, $height || $targ.height);
to
var bmd:BitmapData = new BitmapData($width || $targ.width, $height || $targ.height, true, 0);
Hi,
I’d like to save multiple files on the server. Now the php script overwrites the other images on the server. Is there anyone who knows the answer to check if the image already exists on the server and if yes, simply add a “1″, “2″ and so on after the image’s name.
Thanks!
Found it for those who are interested!
Just replace the text in upload.php to this:
Cheers!
PHP has a built in file_exists() you can use to prevent overwriting the first saved image. You can read more about it here : http://php.net/manual/en/function.file-exists.php
Hey guys!
Thanks for this tutorial!
It works fine for me, I can save the movieclip on desktop, when I try to save on the server I get no error, the output say that it was saved, but when I open the folder on server the image isn’t there, do you know how to fix it?
Thanks! =)
Hi again .. been a few months and ive just discovered a new problem .. has anyone had an issue with this working in IE browsers …
ive run this in FF, Chrome and even safari .. all worked fine as it should ..
but once I use IE it only produces a fully transparent png .. nothing else. it is the proper dimensions but it omits any of the image data .
??
I’m trying to open the .fla file included in the whole package but I get “unexpected file format”. I’m using flash CS4. please, do you know what the problem may be? thanks!
I’m trying to open the .fla file included in the whole package but I get “unexpected file format”. I’m using flash CS4. please, do you know what the problem may be? thanks!
The .fla is empty and just has a reference to “AppMain” as its document class so it’s easy to compile if you have the Flash IDE. I just uploaded another version that is saved back to CS4 so either try this one or create your own .fla and set it to use “AppMain” as it’s document class and you should be good to go.
I can’t tell you how excited I am to find this! I’ve been trying to create my own class to do just about the same thing. I haven’t programmed much in Action Script so I was feeling a little lost.
I do have one question, how would I go about starting to use this on a movie clip that is already in place instead of using the one you are creating? Any pointers?
Gina, you can pass in any DisplayObject you like including a MovieClip in your library. Just instantiate your MC and pass it into the BitmapSnapshot constructor as shown in the example above.
This is probably a stupid question, but how do I pass a movie clip into the function saveToDesktop()? I’m actually importing the package for use instead of attaching it. In the “AppMain” package I have commented out all the ball creation stuff and I’m now trying to figure out what I need to change to be able to use my MovieClip on the main stage instead your _canvas:MovieClip; Do I need to change it to “private function saveToDesktop(canvas:MovieClip):void”?
Gina, if you have a MovieClip on the Stage with say an instance name of “myMovieClip”, you can pass the MC into the saveToDesktop function via :
var img.BitmapSnapshot = new BitmapSnapshot(“myMovieClip”, “myImage.png”);
img.saveToDesktop();
That’s what I needed, thank you!
One more question:
Is there a way to combine 2 movie clips before sending into the saveToDesktop()? I have one mc of a shirt and another mc on top that contains a design. I would like to make one image out of the 2 combined mc’s. Tips on how to go about doing that?
I’m actually trying to combine the images created with BitmapSnapshot.
var img1:BitmapSnapshot = new BitmapSnapshot(this.frontGraphics,”snapshot1.png”);
var img2:BitmapSnapshot = new BitmapSnapshot(this.frontGarment,”snapshot2.png”);
var combo:Bitmap = new Bitmap();
addChild(combo);
combo.bitmapData = mergeBitmap(img1, img2);
combo.saveToDesktop();
}
function mergeBitmap(_data1:BitmapData,_data2:BitmapData):BitmapData
{
var mergedData:BitmapData = _data1;
mergedData.draw(_data2);
return mergedData;
}
of course it’s throwing an error “implicit coercion of a value of typ com.quietless.bitmap:BitmapSnapshot to unrelated type flash.display:DisplayObject. If I understand it correctly, I’m not passing the right type somewhere. I’m thinking that after the “img1 and img2″ are the wrong datatypes for merging? I guess it returns an png and not a bitmap?
Gina,
My BitmapSnapshot class generates a ByteArray of data from the DisplayObject you pass into it so it’s not really designed to marry two BitmapSnapshots together.
You can however marry two DisplayObjects together before creating the snapshot and this should get you what you’re looking to achieve.
Assuming you are building a drawing app that allows people to draw onto a “canvas”, you could do the following.
// generate two images of the canvas in memory //
var bmd1:BitmapData = new BitmapData(100, 100);
bmd1.draw(my-canvas-mc);
var bmd2:BitmapData = new BitmapData(100, 100);
bmd2.draw(my-canvas-mc);
// associate these newly created images with displayObjects
var b1:Bitmap = new Bitmap(bmd1);
var b2:Bitmap = new Bitmap(bmd2);
// composite these two Bitmaps together
var composite:Sprite = new Sprite();
composite.addChild(b1);
composite.addChild(b2);
// generate a BitmapSnapshot from the composited Sprite
var snap:BitmapSnapshot = new BitmapSnapshot(composite, ‘snapshot.png’);
snap.saveToDesktop();
Hope this helps.
YOU ARE MY HERO!!!! Thank you so much! Worked like a charm.