AS3 ImageSaver Class v1.0

ActionScript

ImageSaver ClassMy ImageSaver() Class is ready for download.

Download
» ImageSaver v1.0
» Latest version of ImageSaver on GoogleCode

Features

  • Save a MovieClip, Sprite, Shape, Bitmap, Textfield or other kinds of displayObjects.
  • It doesn’t matter where or how your object is positioned on the stage, it gets the right bounds.
  • Never worry about bytearray’s / encoding anymore.
  • Save your displayobject as JPG or PNG (using Adobe’s encoders)
  • Ready-to-install PHP file.

How to use
1. Copy the ‘save-my-image.php’ file to your server or testing environment (I use WAMP for testing)
2. Use ImageSaver like this example.
// Create saver instance + point to php file on server
var imageSaver:ImageSaver = new ImageSaver( “http://localhost:8080/save-my-image.php” );

// additional: Add eventlisteners.
imageSaver.addEventListener ( Event.COMPLETE, onSaveComplete );
imageSaver.addEventListener ( IOErrorEvent.IO_ERROR, onSaveError );

// Save textfield as JPG with red background
imageSaver.save ( myTextField, “myfilename1.jpg”, 0xFFFF0000 );

// Save bitmap as JPG with red background in low JPG quality (15)
imageSaver.save ( myBitmap, “myfilename2.jpg”, 0xFFFF0000, 15 );

// Save a shape as transparent PNG
imageSaver.save ( myShape, “myfilename3.png” );

// Save a movieclip as half-transparent (red) PNG
imageSaver.save ( myMovieClip, “myfilename4.png”, 0xCCFF0000 );

// handle events

private function onSaveError( e:IOErrorEvent ):void {
trace ( “Image save failed. Error while saving: ” + e.text );
}

private function onSaveComplete( e:Event ):void {
trace ( “Image save completed” );
}
The save-function works like this:
public function save( displayobject:DisplayObject, filename:String, backgroundColor:Number = 0x00FFFFFF, JPGquality:int = 85 ):void

I love to hear your suggestions. Feel free to use it too.

Creative Commons License
Creative Commons Licence

77 responses to “AS3 ImageSaver Class v1.0”

  1. RoofTopWalkder says:

    Sounds great, and can hardly wait to try it (when I free up some time this week).

    Quick question: I’m looking to save the entire stage (made from overlapping movie clips). Is there an easy way to do that?

    Thanks for sharing!

  2. Mark Knol says:

    Hi RoofTopWalkder,

    When your movie is in a container sprite, you could save that sprite using this class. Or maybe you could try to call the document class, because that one is supposed to be a displayObject, right? I hope that would help you further. Just try it out, and post your opinion 🙂

  3. 1. I created a test.fla with the following line on frame 1:

    import com.Main;

    2. In the folder where test.fla was, I copied the folders “com” and “nl” so that they are subfolders, and Main.as is in com subfolder.

    3. I also edited Main.as and changed the php filename to “save-my-image.php”.

    4. I published the test.swf (compiled with no errors) to WAMP server, and also uploaded save-my-image.php there.

    5. When I open the file test.swf on my browser, it is just an empty page. Nothing is drawn on screen (no textfield, bitmap etc.). It seems something is hung.

    ——
    Separately, I tried putting in

    import flash.display.*;
    import flash.events.*;
    import flash.text.*;

    import nl.stroep.utils.ImageSaver;

    in another *.fla I have with a preloader, and it seems the swf file hangs at the point of the imported package. The preloader hangs and does not proceed to Frame2 as it’s supposed to.
    ————————
    What am I doing wrong?

    Thanks for your time to answer this.

  4. Mark Knol says:

    @RoofTopWalkder:
    I created a testfile (.fla) incl. a main class for you. This works. You should take a look at this one:
    http://projects.stroep.nl/imageSaverTestProject.zip

    It saves the whole stage and a single movieclip. Hope this will help.

  5. Sorry to be a nuisance… but I’m still not able to get it to work. I tried a few things:

    A. NO EDITS
    1. Copied testfile.swf to the server.
    2. Renamed “save-my-image.php” to “save.php” on server as that the latter is being referenced in the new Main.as
    3. Called testfile.swf from browser – the image and textfield displays, but no image file was created.

    B. EDITS
    1. Opened up testfile.swf and found no scripts (maybe it was an earlier version?) so I added “import Main.as;” (Main.as was in the same folder as textfile.fla) on frame1.
    2. Compiled – got the error “1180: Call to a possibly undefined method addFrameScript” on Main.as line 1. Turned off “strict mode” in Flash and the warning went away.
    3. Uploaded new testfile.swf to server.
    4. Called testfile.swf from browser – the image and textfield displays, but no image file was created.
    —————–
    What am I doing wrong?
    Thanks for your help!

  6. Mark Knol says:

    Check the following thing:

    -What if you use just use my test fla? Do you get error’s on that one too?

    – Try pointing to “save.php” instead of “http://localhost:8080/save.php”and publish the swf in the save directory as the php file.

    -Have you tested if the save.php works? (open in browser, if you just get a blank page, it is working)

    – Are there any other compile errors? You talked about a preloader. Isn’t there a bug in the preloader (because thats a bit your problem 😉 ) Fix that thing!

    – Do you use FlashDevelop (not necessary)? Because FlashDevelop automaticly handles the imports.
    – Otherwise, check adobes livedocs for handling imports.

    notes:
    – There is no script in the fla, I have create a document class, wich is linked in the properties window to main.as.

  7. RoofTopWalker says:

    Changing “http://localhost:8080/save.php” to “save.php” did the trick! Thank you! testfile.swf created a nice jpg file.

    And I managed to get it to work in my fla file. I did it by following your script in the article (rather than using Main.as), incorporating relevant in the frame itself and calling ImageSaver.save(myMovieClip,”myClip.jpg”,0xFF252525,25);

    It successfully created a nice jpg file. However:

    1. no matter what I entered as the quality size (e.g. 45, 75), it always generated the same file size, which was the same size as the *.png file, had I had specified “myClip.png” instead of “myClip.jpg”. Not sure whether I misunderstood something here.

    2. The way I did the imageSaver.save() function was to put it in an enter-frame listener. The idea is to auto-save whenever we land on frame 3 and stop (the movieclip will change each time). However, I could only get it to save the first time it enters frame 3. Subsequent times the playhead lands on frame3 (after proceeding elsewhere), there is no save.

    Even if I removed the listener and enterFrame function, and just left the imageSaver.save() function in Frame3 (so that imageSaver.save() will run everytime Frame 3 is called), it still doesn’t work. This was what I tried originally.

    The code:

    stop();

    addEventListener(Event.ENTER_FRAME, savePic);

    function savePic(event:Event) {
    if (currentLFrame == 3)
    {
    imageSaver.save ( smartTag, “stage” + String(page) + “.jpg”,0xFF252525,25 ); //0xalpha,R,G,B
    output.text = “Saving page ” + String(counter) + “!”;
    }
    }

    Any ideas are greatly appreciated.

  8. Mark Knol says:

    1. I updated the file, so the JPG functionality should work OK.
    2. Don’t you mean :
    if (currenframe == 3){}

  9. RoofTopWalker says:

    1. JPG works great now. Thanks!

    2. It was a typo, should’ve been currentFrame (which didn’t work). I did more tests and found:

    a. calling imageSaver.save() multiple times *in the same frame* works; but

    b. if I call imageSaver.save() in one frame, and then leave the frame, and either:

    i) call it again in another frame (with different savefile name/type), OR

    ii) return to the original frame and call it again (same savefile name/type as first time)…

    the second call silently fails. No error message is triggered either.

    Any ideas?

  10. Franto says:

    Hey Mark, thank you for the class. Can you please explain me, why you did not extends EventDispatcher but rather implement addEventListener and removeEventListener? I’m just curious…

  11. Mark Knol says:

    Hi Franto, Thanks for your feedback. Do you think it’s better to extend the EventDispatcher in this case? I wasn’t very sure for that.

  12. Maximillion says:

    thanks for the tutorial, but i am little lost. you spoke earlier about a save.php page, the one that i have is save-my-image.php. In that page i am getting an error

    fclose(): supplied argument is not a valid stream resource in C:\inetpub\wwwroot\ImageSaver\save.php on line 9

    and i dont know php well enough to fix it.

  13. Maximillion says:

    scratch previous message. I got it to work but i am still a little confused on where the images are stored once they are saved. my swf told me the files were saved but did tell me the location

  14. John says:

    Any ideas how might this work with a mask? For example, you have a circle mask over a photo and then the cropped circle photo is saved with transparency?
    Thanks!

  15. Mark says:

    John, you have to put the mask in a new movieclip and point with the imagesaver to that movieclip.

  16. John says:

    Yeah I thought that but it seems that bitmapdata doesnt support masks? I’ve got some time today so I’ll look into it.

    Thanks

  17. John says:

    I’ve almost got it. The mask is a bit off x and y which can probably be sorted ok but my new problem is that it’s also exporting all the transparent pixels that the mask creates, i.e. all the area underneath it. Hmm

  18. John says:

    Done it! I’ll post up the code later.

  19. Crnvalle says:

    Yo Mark,

    Thanks a lot for your class. I was just about to build something similar when your solution dropped from the sky (google :-)).

    I am – btw – using it to build spritesheets out of animations in flash.

  20. venkat says:

    hi giuys,

    Iam new to AS3 and i want to implement this functionality in one of my applications.iam bit confused .can anyone provide me with the fla source file in which this functionality is implemented.

    regards
    venkat

  21. venkat says:

    hi

    i implemented this code.but when iam saving that image .the trace message says that the image saving is complete .but there is not image in the png generated.it is empty.can anybody help me with a fix

    venkat

  22. Mark Knol says:

    @venkat; Did the serverpath is correct? Note that the PHP-file (included in this project) saves the image in the same folder as the PHP file, not in the same folder as the SWF.

  23. Alice says:

    Hey, I wanted to use your class, but it turned out, that when object (for example Movie Clip) has some filters applied (for example alpha or color transform) your class doesn’t save those things. It simply ignores all “additional stuff” and saves movie clip “as is”.
    Is it possible to fix this? I would really appreciate some clues at least… Thanks in advance 😉

    [and by the way – your ribbons are amasing! 😀 ]

  24. Mark Knol says:

    Hi Alice, thanks!
    Quick fix: You should copy your mc into a container movieclip and save that one.

  25. Love the class and the fact that you beat adobe to it, they now have a similar how to up. i’m have having some problems with transparency getting lost in pngs. it seem like a transport issue i can see in flash that the movie clip to be saved should have transparent but when the file is loaded back in, sent to the server and requested it comes back with black where the transparency used to be.

    this seems to only happen with some servers, i’m using php.

    do you think that php maybe throwing an error or some that throws off the saved file?

  26. heads up.

    the getExtension function is not implemented in the best way. it only allows for one ‘.’ in the filename. while i know that the ‘.’ isn’t the best character to throw around in a filename i started getting jpg when i expected png because i was trying to save a file ‘./images/myimage.png’ and getExtension function would return ‘/images/myimage.png’, which then used the default jpeg encoder. this is what was causing my black background.

    i suggest somthing like the following

    private function getExtension( filename:String ):String
    {

    var arr = filename.split(“.”);
    var len = arr.length;

    return arr[len-1];
    }

    anyway love the Class it is amazing and the perlin randomizer is very cool. thanks for the good work.

  27. anu says:

    hi first of all kudos to mark for giving it as an open source… everything is working just right..the mask thing as well, but but… after applying mask….the image gets masked but the image dimensions are same as stage..

    is there any way we can contol the image dimensions as well

    lets say my stage is 400 x 400

    i created a movieclip 400 x 400..i v now put a mask of 100 x 100

    the image now generated is 400 x 400 where in 300 x 300 is transparency

    cant i have image exactly 100 x 100

    any help will be great

    regards

  28. TuanDuy says:

    I have been working with the AS3 ImageSaver Class v1.0 and it appears perfectly with server, please help me to save and open it to and from the user computer without server and flex(just with AS3)
    thanks

  29. Mark Knol says:

    @anu, if you need a specific image size, then create a bitmapdata object and draw your mc into it (using draw() function).

    @TuanDuy, that’s only possible with an AIR application or with the FlashPlayer10 player.

    @Nick Trienens; thanks for you great suggestions and tips! But I’m not sure if its possible to throw an error to flash back again from php.

  30. anu says:

    you really deserve a big hand..you been replying after you have contributed th eopen source..thanks a ton mark..hats off to you

    iwill post my full source code once i am done with what i m creating 🙂 for others ..may be this way i could add to your contribution 🙂

  31. anu says:

    great i have done it 🙂 exact mc size image..jpeg and png.. thanks mark for your guidence..

    one little thing please..i dont want th eimage to be generated automatically..what should i do to create it using a button :???

  32. anu says:

    i did it 🙂 yipee…okay one more thing plz mark…why PHP? cant we do this in aspx .NET i mean

  33. Mark Knol says:

    @anu, to use it with a button use something like this

    var imageSaver:ImageSaver = new ImageSaver( “http://localhost:8080/save-my-image.php” );

    myButton.addEventListener ( MouseEvent.CLICK, onButtonClick );
    function onButtonClick ( e:MouseEvent ):void
    {
    imageSaver.save ( myMC, “coolimage.png” );
    }

  34. Mark Knol says:

    You also can use ASP.net, but you should write your own file for that. You need to get the raw post data and write that into a file.

    If you got that file, please send it to me, so I can include it in the project 🙂

  35. Mark,

    My generative artworks are used for giclee printing on canvas. Printing from SWF to PDF in Flash lost the glow effects. I hope your ImageSaver could help me. My questions are:

    1. Can I control the DPI or PPI of he jpg file exported from AS using your ImageSaver class.

    2. Will the ImageSaver export jpg with all the gradient,, glow or shadow effects?

    3. Is it possible ImageSaver export image to TIFF or EPS?

    Thank you.

  36. matt says:

    Works a treat.
    What’s the best way to add a progress handler in so I can display a preloader?

  37. EM says:

    Hi, sorry to bother you – I’m trying your test files that you included in: http://projects.stroep.nl/imageSaverTestProject.zip and I just can’t get it to work.

    I extracted the folder and copied over the “save-my-image.php” file from your other zip (since it wasn’t included in the TestProject.zip)

    I have the files and folders uploaded to my server as such:
    testfile.swf
    Main.as
    save-my-image.php
    nl
    com

    In Main.as I changed the imageSaver var to point to:
    var imageSaver:ImageSaver = new ImageSaver( “save-my-image.php” );

    In testfile.fla I included the line: import Main;

    Any ideas what I could be doing wrong? Your help is greatly appreciated. This class is exactly what I need.

    Thanks!

  38. EM says:

    Hi again, I was able to get a very simple test working. Not the one provided in your zip (still can’t get that one working), but a very basic test I did on my own.

  39. Mark Knol says:

    Hi there EM, note that save-my-image.php must be on a php-machine or use a full http path to the php file.

  40. EM says:

    Hi, thanks for getting back to me, Mark. Yes, the php file is on my php server (running off of Pair networks) and the swf I was testing was via the web server as well – and all were in the same folder. So the swf was tested via it’s url on our hosted account. When I tested the php file on it’s own sending it a test filename, it worked and was able to create the test filename in the directory. So I don’t think that was the issue. There must have been an issue with how I was using the external Main.as in the testfile.fla. Somehow testfile.fla wasn’t able to load Main. I was able to get a simple test working without using Main.as. Just can’t seem to get the exact files in your test zip to work.

  41. ian says:

    Great little class. Not too much overhead, easy to use, took me less than an hour to incorperate it as a ‘save this shirt’ option in my custom tailored shirt designer.

    http://www.deoveritas.com/shirtDesign.php

    Nice work as a whole, keep rocking that bitmapdata class.

  42. Gwen says:

    Very nice indeed!
    Sure beats the copy/paste method i used to have 🙂

  43. Parrudex says:

    great job…

  44. danno says:

    how do i go about saving the masked image like both john and anu have asked above? each of them said that they would post their code but neither have :/ i’m looking to do what anu had laid out:

    500×500 stage size.
    100×100 mask size.
    wanting to output the 100×100 masked image.

    i’m a little confused with what you had put in response about creating a new bitmapdata object to save it. any help you could give me with the simple-to-understand steps to export a masked image would be extremely appreciated.

    thanks so much!

    rocksteady,
    danno~

  45. Mark Knol says:

    @danno:
    I think if you put your mask and the contents into a new movieclip and point with the ImageSaver to that clip, it will help you solve the problem.
    Otherwise check out my crop util class: http://code.google.com/p/stroep/source/browse/trunk/nl/stroep/utils/CropUtil.as
    Info: http://code.google.com/p/stroep/wiki/CropUtilClass

    I hope this will help!

  46. Levi says:

    This rocks! Thanks for sharing!

  47. Lasse Hall says:

    this is exactly what I am looking for.

    BUT my challenge is that the file needs to be saved with 150 DPI. Is that possible to in some way, decide the resolution?

    The file is to be used for print and 72 is not enough to make a good print.
    cheers / Lassse

  48. frankvb says:

    This is excellent actionscript!!

    I only had a problem saving a sprite object with several bitmap children. It saved a picture, however the picture was completely blank. I solved it by drawing the children in a bitmapData object.

  49. Chris says:

    Thanks for the script.

    I am having a strange problem though. I am using this in IIS 7 on a live site and every now and then the image is not saved but it does not through up any errors. I have checked my server logs and it does not seem to be calling the save file, but does every other time.

    Any ideas?

    Thanks
    Chris

  50. Mark Knol says:

    Hi Chris, I hope you don’t use the php file on your IIS server right? What asp code do you use for saving the data?

  51. Chris says:

    Hi Mark,

    Yes I do use PHP script to save the file. This works 90% of the time but some times it does not. After investigation, I do not think it is the PHP file, I checked logs which shows that the save php file is not called when the error occurs. It seems that the problem lies with calling the php script from the flash script.

    Can you confirm which versions of Flash this works in? I had one person where this failed every time, so I can only assume it is there machine with the problem.

    Thanks for your response.
    Chris

  52. adam says:

    Hi Mark

    Great code. It worked just fine for me with those few simple mods. Got it working with a button, thanks so much for sharing your code and for the awesome follow up in the comments. Too bad this is AS3 as the project I am trying to implement is an AS2 project.

    Was wondering if it were possible to ammend the filepath to something other than the same directory as the PHP file? Something like:

    imageSaver.save ( myMovieClip, “database/images/avatars/myfilename4.png” );

    If these directories already existed would this work?

    Cheers, great work
    -adam

  53. syaam says:

    Hi,
    I want to save movie clip as jpg or png.. I drag some images from image pool and dropped onto movie clip. after saving that movie clip , those dragged images were not appeared in that image. How to save movie clip with those images?

    Thanks in advance

  54. syaam says:

    Hi, i am able to save total document..not able to save individual movie clip..i already told u abt the functionality. drag images from image pool and drop onto movieclip.. i want to save movie clip with those dropped images…

    Those images are not childs of movie clip..may be this is the problem i think…
    Can u have some pointers regarding that?

  55. syaam says:

    sorry for this statement..those dragged images were not appeared in that image….

    correct statement is those dragged images in movie clip were not appeared in the movie clip after saving

  56. Mark says:

    @syaam: nice to hear things just work out.

    @adam: Sorry the class is not available for AS2. About the filepath; I think this should be solved with PHP, not flash.

  57. syaam says:

    Can u have any pointers for my problem?

  58. Mark Knol says:

    Everything inside an movieclip can be saved. I guess you need to restructure a bit to have a container-clip which contains all clips that need to be saved. All stuff that need to be saved must be childs.

    Another solution; If you want to combine things from other levels you can create your own bitmapdata object too and use the draw() function to blend it into one picture. Hope this helps.

  59. syaam says:

    Hi,
    Thanks for ur suggestion…

    How to draw bitmap data object in a situation like that? Could u explain a little more? Logically those images are also exists on same area… how to merge pixels of movie clip data with those images data?

    Thanks

  60. syaam says:

    sorry, not exactly merge…I think we have to do blend on those objects

  61. syaam says:

    Could u give me little bit explanation for my problem?

  62. Mark says:

    @syaam: You could create a bitmap and draw things into it like this:

    [code]
    var bmd:BitmapData = new BitmapData(800, 600, true, 0x00FFFFFF);
    bmd.draw(mc1);
    bmd.draw(mc2);
    bmd.draw(mc7);
    bmd.draw(mc14);

    imageSaver.save ( bmd, “myCombinedStuff.png” );
    [/code]

  63. Mike says:

    excellent class! can you point me to a php script that would allow the final product to be emailed?

  64. Mark says:

    @mike: Because the image can be saved on your server, you can make a variable in your mailtemplate, which should be replaced by the path to the image (the php file already knows this file).

  65. Mike says:

    do you know of a template php script that I could work from with such a variable to make this work? btw, the email address change based on input into a Flash field. thanks again, Mark…

  66. Jozef says:

    Hi ! great work ! It is possible to show exported image on a new blank page? Should I edit PHP script or something in ActionScript?

  67. Mark says:

    You could use navigateToURL(new URLRequest(“imageName.jpg”),”_blank”) after saving. (use it when you receive Event.COMPLETE)

  68. Jozef says:

    Thanks, it´s working. How it make without saving on server, only display in browser? Can I use GD library?

  69. amitkhanna says:

    Hi there,

    I was trying to use your class today but no luck. It just saves me a 0kb jpg or png.
    I was earlier trying the regular method (byteArray + JPGEncoder) but even that wasn’t working.

    At least your class is saving a file on my server & saves a lot of typing 🙂 but still no image.

    Can you please help me with this.
    Appreciate your response

    Thanks,
    Amit

    p.s. you blog design is really cool 🙂

  70. Mark says:

    Hi amitkhanna, Strange.. What is your code to save the image? Did you used the PHP file, and is it running on a server? What happens if you open just the PHP file? Is the movieclip/sprite you are trying to save filled?

  71. Mark says:

    Hi amitkhanna, That is strange.. What is your code to save the image? Did you used the PHP file, and is it running on a server? What happens if you open just the PHP file? Is the movieclip/sprite you are trying to save filled?

  72. amitkhanna says:

    Hi Mark,

    Its strange my files are not working online but everything’s working great on loacalhost. Is there some settings for php which my server might be missing?

    Thanks for the class though, it saves a lot of typing 🙂

    Amit

  73. RonL says:

    When I test the save.php file I get this error:

    Warning: fclose(): supplied argument is not a valid stream resource in /home/xxxxx/public_html/ComingSoon/save.php on line 9

  74. Tom says:

    I get the same error as RonL =(

  75. James says:

    hi Mark,

    thanks for sharing, it absolutely works great 🙂
    I was wondering how I can save the images in another folder than the one which contains the php file.

    thanks,
    James.

  76. Mark says:

    … 11 years later, but In case anyone tries this, you need to replace this in save-my-image.php

    replace:
    fwrite( $fp, $GLOBALS[‘HTTP_RAW_POST_DATA’] );

    with:
    fwrite( $fp, file_get_contents(“php://input”) );

    The former is deprecated.

  77. this article helps me to gain some knowledge.

Say something interesting

Please link to code from an external resource, like gist.github.com.