cash loans
3 April 2008

Using AS3 to Upload and Encode Images

UPDATE: 10/24/08
==============
After many requests, I’ve updated the demo and source files to work in IE6 (turned out to be a pathing issue), as well as Flash Player 10. FP10 disallows opening the download dialog without user interaction, so I’ve a download button to accommodate this change.
==============

Since launching Logobama, we’ve had a number of requests for the project source code. The process of saving images from Flash turns out to be a relatively simple one with Actionscript 3, and after some searching, uploading Flash encoded JPEGs to a web server was pretty simple as well.

With the Logobama project, we had three main objectives:

  1. Upload an image into a Flash file
  2. Encode a JPEG with AS3
  3. Post the encoded image to a web server

In the case of Logobama, we also posted the saved image to a Flickr gallery, which was done using the phpFlickr library created by Dan Coulter. Thumbnails are automatically created with phpThumb.

The main engine behind this project is a combination of elements from the Adobe AS3 Corelib, and the very handy UploadPostHelper Class created by Jonathan Marston. There is also a small PHP upload script included in the source, along with TweenLite, which has quickly become our favorite tweening engine.

The basic system within the code nearly mirrors the Logobama project objectives:

1. Use the FileReference Class to upload an image:

var file : FileReference = new FileReference();
file.browse( new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" ) ) );

2. Create a snapshot of the flash movie with the BitmapData.draw() method:

// set up a new bitmapdata object that matches the dimensions of the captureContainer;
var bmd : BitmapData = new BitmapData( captureContainer.width, captureContainer.height, true, 0xFFFFFFFF );
			
// draw the bitmapData from the captureContainer to the bitmapData object;
bmd.draw( captureContainer, new Matrix(), null, null, null, true );

3. Use the Adobe AS3 Corelib to encode a JPEG:

// create a new JPEG byte array with the adobe JPEGEncoder Class;
var byteArray : ByteArray = new JPGEncoder( 90 ).encode( bmd );

4. Post the encoded image to a web server with the help of the UploadPostHelper Class and a basic PHP Upload Script (included in the source files):

// set up the request & headers for the image upload;
var urlRequest : URLRequest = new URLRequest();
urlRequest.url = 'image.php?path=images';
urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = UploadPostHelper.getPostData( 'image.jpg', byteArray );
urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );

// create the image loader & send the image to the server;
var urlLoader : URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load( urlRequest );

So there you have it, an easy way to upload images into flash, edit them, and post the encoded JPEG result to a web server without the need for any fancy remoting or server-side computation.

Since all the above code is available under a Creative Commons Share Alike license (or similar), we’ve decided to make our source code for this project available as well. The functionality of this example was intentionally minimized to showcase the features outlined in this post. Enjoy, and please feel free to reply with comments, questions, or revisions.

posted by Shaun Tinney

thinking about… AS3, Flash

56 Comments…

  1. Dane said…

    Thanks for sharing Shaun, I’m sure this will come in handy some day.

    10:51 am / April 3rd, 2008

  2. Steve Jones said…

    Thanks a lot for this – very neat stuff indeed, and my just be the post that saves my lily white ass.

    I owe you one.

    5:42 am / April 10th, 2008

  3. Jonathan said…

    You are the man! This is the single best post I’ve found for image upload/export using flash. Thanks so much.
    I’ve been trying to do all of this in AS2 and PHP. It’s hard to believe you can do all of this inside AS3.

    5:34 am / April 26th, 2008

  4. [...] http://labs.findsubstance.com/2008/04/03/as3-upload-encode-images/ [...]

    3:11 pm / April 30th, 2008

  5. We have used this process and had great success.

    One caveat for using this approach in Internet Explorer and any ActiveX wrapper… In these instances, the player doesn’t seem to like some basic response headers. Specifically we were trying to return a RESTful ’201 (Created)’ header and Flash Player would throw a #2032 IOError. It was solved by using the basic ’200 (OK)’ response header.

    Probably not a common issue, but it took a long time for us to figure out what was going on.

    Thanks, Shaun

    4:51 pm / May 2nd, 2008

  6. cosmoz said…

    Thank you very much, the code work like a dream. Again thanks for shared.

    A

    12:08 am / May 6th, 2008

  7. Sly said…

    Good example !
    Is it possible to add a “loading bar” to show the progress of the upload ? I suppose that yes. I will try.

    6:47 am / May 22nd, 2008

  8. [...] so of course it didn’t work and I ended up having to piece together (very helpful) bits and bobs from various sources until eventually something somewhere clicked into [...]

    9:23 am / June 4th, 2008

  9. Thank you for posting these extremely helpful classes and tips. I thought I would point out, however, that the line starting with “file.browse…” should have 3 closing parens.

    Thanks,
    -Dan

    6:11 am / July 3rd, 2008

  10. Shaun Tinney said…

    Thanks Daniel, updated.

    6:29 pm / July 4th, 2008

  11. sebastian said…

    very nice work, thanks a lot. i wonder if you also wrote something like “ScalableImage.as” to adjust the image size?

    7:35 am / August 4th, 2008

  12. Sebastian,

    You might want to check this out:
    http://labs.findsubstance.com/2008/07/07/as3-scaling-techniques/

    This should do what you need, or at least get you started in the right direction.

    Good luck.

    4:22 pm / August 4th, 2008

  13. sebastian said…

    thank you, that helps me a lot. hoping not to be too annoying, do you have any idea why the upload doesnt work on IE < 7? regards from bavaria, sebastian

    3:16 am / August 5th, 2008

  14. [...] Using AS3 to Upload and Encode Images – Great article on how to customize an image in Actionscript 3 and POST to a server On Bookmarks @ 05/08/2008 | By delicious [...]

    5:20 pm / August 5th, 2008

  15. sebastian said…

    maybe you have a hint, why obama.com is working with IE6 and the demo not? thanks …

    5:05 am / August 6th, 2008

  16. Shaun Tinney said…

    Hey all,

    I’ll post an update as soon as I find a few extra minutes to troubleshoot this IE issue. It’s possible that I stripped out one thing too many while preparing the example source code.

    9:43 am / August 13th, 2008

  17. byte said…

    a black cold guiness for sending the image to a predefined email:)

    12:10 pm / August 19th, 2008

  18. DVB said…

    I’ve looked thru your source and the AS3 language reference pages…but I’m still not 100% sure on something.

    Do you HAVE to FIRST upload the image to the server and then download into flash in order to manipulate the file in flash? (Eg. resize, get a preview etc)

    Is there no way to just filereference.browse() and then pull that image into flash, provide a preview, resize in flash and THEN upload?

    7:34 am / August 24th, 2008

  19. Shaun Tinney said…

    @DVB I would love to be able to do something like that, but the flash player security prevents that kind of activity from a remote swf. You can definitely pull that off with AIR though.

    You can read more about file upload and download, but the basic idea is that “the FileReference class allows you to upload and download files between a user’s computer and a server.”

    Adobe AIR is a really cool way to develop applications, especially since it only extends current AS3 functionality, without the need to learn a whole new programming language.

    11:02 am / August 26th, 2008

  20. Rob said…

    Is anyone else having a problem with stream error 2032?

    I’ve been wrestling with this all day and I can’t figure out why it’s happening. The URL I’m feeding it is good and it’s in the same directory on the same server as the SWF, so it shouldn’t be a domain permissions issue. If I just have the URLLoader load the URLRequest without setting URLRequest.data it works fine (except of course that it doesn’t send my jpg) but if I feed it UploadPostHelper.getPostData it gives me the 2032 error every time.

    Some people have mentioned having issues with IE, but this happens in Firefox as well. Has anyone else had this issue?

    12:32 pm / September 6th, 2008

  21. Ryan said…

    Hey, I did a similar example on my blog using ASP.NET webservices for anyone who is interested in that….

    http://ryanbosinger.com/blog/2008/saving-images-with-net/

    8:09 am / September 19th, 2008

  22. [...] many requests, I’ve updated the demo and source files for the wildly popular labs post Using AS3 to Upload and Encode Images. Hope everyone finds it [...]

    11:43 am / October 24th, 2008

  23. [...] http://labs.findsubstance.com/2008/04/03/as3-upload-encode-images/ [...]

    8:00 pm / November 3rd, 2008

  24. Mescalina said…

    Hi, by the way great job!
    I’m succesfully using your lib to create an image uploader that resized images locally without needs of upload them before. This using the new FileRefernce methods introduced with Flash Player 10.

    Everything works fine, but it seems not possible to have a progress of the upload. The post data are passed and then the OPEN Event is called. Am I right?

    I’m not able to find any way of having a progress feedback.. Any idea?

    Bye, and thank you.

    1:36 pm / November 21st, 2008

  25. Mescalina said…

    Flash reference:

    In Flash Player 10 and later, if you use a multipart Content-Type (for example “multipart/form-data”) that contains an upload (indicated by a “filename” parameter in a “content-disposition” header within the POST body), the POST operation is subject to the security rules applied to uploads:

    The POST operation must be performed in response to a user-initiated action, such as a mouse click or key press.
    If the POST operation is cross-domain (the POST target is not on the same server as the SWF file that is sending the POST request), the target server must provide a URL policy file that permits cross-domain access.
    ______________________________

    With flash 10 your script needs a user iteraction such as a click to run, otherwise it throws a security error.

    In this way it seems to be impossible to menage multiple uploads without a user iteraction for any of them, the only way I found is to call all files load with one click, but in this way I’ll send many php requests at the same time with a lot of data and I think that can crash everything up..

    4:43 pm / November 21st, 2008

  26. Jules said…

    THANK YOU!
    I am a newbie to AS3, heck…………..AS in general , but am very familiar with oop. It has been a few years, but, thanks to your code and comments, it all came flooding back. I think you just saved my lilly white!

    I ended up using the classes I needed and taking snippets here and there to get just what I needed. You have saved me eons of time.
    Again, Thank you

    4:57 pm / December 3rd, 2008

  27. Andy said…

    This rocks, thanks. Any hints as to how to make the “mask” the image is seen through semi-transparent? Maybe needs some bitmap caching for a semi-transparent mask…?

    9:29 am / December 12th, 2008

  28. Kevin said…

    When I found this post I wanted to punch myself in the face to make sure I wasn’t dreaming. I got out of my chair and walked around the office with a huge grin on my face. I was in such a good mood I asked out this girl from the coffee shop that I like.

    THANK YOU for this very informative and helpful post.

    Posts like this kick Live Docs square in the balls.

    6:17 am / January 5th, 2009

  29. andres watson said…

    is it possible to get the logobama source code?

    6:15 am / January 8th, 2009

  30. randygland said…

    Hey, I’m building a flex ap for the new flash player 10 which involves FileReference.browse to select a local image, then applying some special FX to the image and allowing the user to post the image back to a remote server.

    I’d like to put a link publishing the result and the source code for anyone interested, as I will probably use shaun’s method posted here.

    I’ll let u knoow how it goes,

    OKTHXBAI

    3:03 am / January 9th, 2009

  31. Nick Polet said…

    Nice code.

    Is it possible to run this on multiple files with the FileReferenceList? I am having trouble uploading multiple ByteArray jpg files to a server using this php code. Does anyone know how this can be done?

    Thanks

    5:26 pm / January 12th, 2009

  32. Olivier said…

    Lol good use of webspace that logobama….

    9:12 am / January 13th, 2009

  33. Matt C said…

    To Nick Polet – just to let you know, I got this to work with multiple files. You can select as many as you want and then go through the list to upload them (resizing them as needed).

    Thanks for this code, it was JUST what I was searching for !!!!

    11:03 am / January 20th, 2009

  34. Nick Polet said…

    HI,

    I got this working with multiple images, but it doesnt work when you use it on a live server. The files are not sent to the server in anyway.

    I have been looking around for a workaround, but there is not much in the way of using this method to upload files. I have found a references about this and will post anything up if I find out a good solution.

    10:05 am / January 26th, 2009

  35. lauren said…

    Many thanks for the files!
    I just wondered if there might be the possibility of a file name clash – if two users upload an image with the same name? (Seeing as the upload files are not renamed) Is there a way around this or am I missing something?

    6:44 pm / January 26th, 2009

  36. GNative said…

    love the fact that you have a textmate project file in the source.. smiles

    7:11 am / February 3rd, 2009

  37. cyrt said…

    does the upload only work with JPEG files, or can it be used to upload any file??

    4:55 am / February 18th, 2009

  38. Isaac said…

    Hi!

    i have a problem…the example is working but doesn’t upload file in server… the progress bar is working too…but then, I can’t see view any image..

    :(

    Thanks

    7:28 am / February 23rd, 2009

  39. randygland said…

    hey, nice classes…

    Just one problem:

    I’ve used the JPGEncoder class, and wondered if anyone had managed to find away to encode a JPG without such a massive cpu load.. as the jpg encoding crashes my entire operating system for a few seconds, and prevents any kind of progress animation in the application.

    Is this innevitable? or is there a work around?

    10:53 am / March 20th, 2009

  40. randygland said…

    I’d also like to know how to get the Progress data of the upload to use in my progress bar.. as the ProgressHandler in this example shows the bytes loaded of the php script file the upload uses.. not the bytes uploaded of the encoded JPEG itself.

    9:53 am / March 24th, 2009

  41. randygland said…

    Probably the updated version of this stuff will solve my problems :)

    http://labs.findsubstance.com/2008/10/24/updated-using-as3-to-upload-and-encode-images/

    will try and see ty :)

    10:04 am / March 24th, 2009

  42. randygland said…

    nope. it doesn’t. Can’t do anything with the Progress event of URLLoader to show the uploading of the encoded JPG.

    + encoding the JPG still completely freezes my whole operating system.

    :(

    9:40 am / March 25th, 2009

  43. This is a great tutorial, but its just a bit much for me.

    Is there any way I could use this and just simplyfy it to the point where all you have is the following?

    a input text box to put a title
    a input text box to put a url
    a input text box and a button to upload the image with
    and a text area to put a description
    a button for submitting this

    and to make it better, a way to have the text go to a mysql database, and the image of course got to a folder, but have the location of that folder and or the image name be placed in the database with the other info.

    thanks

    8:39 pm / April 5th, 2009

  44. Michael Xue said…

    Thanks for sharing this! I realized that the included swf doesn’t even require server side script to preview images locally. Incredible! But how is that possible in Flash 9?

    Looking through your source, it seems like php is required to get this working. After compiling, the new swf would no longer show local previews. Why is that?

    3:04 pm / April 7th, 2009

  45. Lucas said…

    Hey man, excellent file. I was wondering if you can give a hand with something. I need to create a movie pretty much like yours, but instead of uploading it to a server I just want to show it in a container (and resizing it). I dont know if I explain myself good.
    It would be a browse button, and a “show” button that put the image in a container. Thats its!

    thanks

    10:21 pm / April 20th, 2009

  46. randygland said…

    as it says in the tutorial, in fp9 or lower a serverside script is required, just to select a image on your computer and view it “locally” inside flash.

    3:42 am / May 1st, 2009

  47. Lucas said…

    Yes, I Know, but FP 10 allow the user to do it with out a serverside script. They´ve changed the FileReference class, but I cant make it work, if you can help it would be nice!
    Thanks

    10:12 pm / May 3rd, 2009

  48. arthur said…

    A huge time saver, thank you for sharing this with us.

    9:13 am / May 15th, 2009

  49. Ademus said…

    FP 10 allow the user to load locally an image with out a serverside script ? They´ve changed the FileReference class?

    please informations about that, thx…

    1:49 pm / June 6th, 2009

  50. Felipe Marquardt said…

    Thanks for sharing this incredible classes. I have one question that have been asked here before but I can´t figure it out how to solve. I´m trying to resize and rotate the loaded image, but when creating it, it comes in the original size. Tried to resize m_capture but with no results. Anybody has any ideas?

    Thanks

    2:41 pm / June 9th, 2009

  51. averyprog said…

    Hi there everyone,

    Awesome script!

    I’m having some problems with the security settings though when creating files. Uploading works fine, it’s just creating the jpgs afterward.

    When the files are on the server i get a security error #2170: Security sandbox violation: mysite.com/swf/image_creator.swf cannot send HTTP headers to mysite.com/image.php?path=output/.”]

    I’ve tried a bunch of things, like adding a very lenient crossdomain.xml

    Perhaps i’m formatting my allowdomains wrong?

    currently i have:
    Security.allowDomain( ‘http://my-site.com’ );
    Security.allowInsecureDomain( http://my-site.com‘ );

    Thanks!

    6:29 pm / June 11th, 2009

  52. Lucas said…

    To Ademus: Check on google “filereference class flash player 10″ You will find a lot of examples, Im already using it.

    2:47 pm / June 14th, 2009

  53. chazbot said…

    I’m a little unclear about the instructions here… if someone could help me out it would be greatly appreciated:

    Step 1 would need to not only browse to the file (as the code shows), but also upload it and then re-download that file into flash to then be accessed as a bitmap, correct? (for flash 9)

    If that’s correct, the image is actually being uploaded twice, correct? Once to be loaded into flash, and again during the multi-part post?

    I’m trying to use this method to upload an image, but my server *REQUIRES* a multi-part post for all uploads, so I can’t get around that 1st (normal) image upload (because I can’t make a bytearray of something that’s not in flash yet).

    Thanks in advance

    5:34 pm / June 22nd, 2009

  54. Tom said…

    You may also need to do more in the way of security checks, for example I tested if it was possible to upload a PHP file and it was, this means people could use your domain for hosting phishing files (plus many other things).

    In a version I made some time ago I fixed this by removing the filename from the client side code and created it at the server.

    http://labs.findsubstance.com/d/as3-upload-encode-images/uploads/test.php

    11:20 am / June 30th, 2009

  55. lee said…

    hi there

    can you please help me? I am trying to get this to work and it wont. how am I supposed to organize all of the folders on my server in order to have this work?

    8:48 am / July 1st, 2009

  56. jimb said…

    Hi
    There is one remaining Mac only bug which I believe is a bug in the flash player.

    Immediately after uploading an image in either firefox or safari, try dragging the image.
    There is NO smooth drag and drop.
    Click anywhere OFF the browser, then select the browser again.
    Smooth drag and drop returns.
    Weird!!!!

    10:12 am / September 4th, 2009