Take a webcam snapshot in Flex 2.0

The bitmapdata class is also represent in Flex offcourse but finally I had the time to test a few things. In this little article I want to show you how you can easily capture a snapshot from a webcam in Flex 2.0. Because I want to do some more experiments later on I created an actionscript component that immediately embed the webcam image in a Panel. So we need to extend the Panel class to make our custumized WebcamPanel class. This sound difficult but it really isn't. Let's go ahead !
First make a new Flex project by choosing File > new > Flex Project. Give your project the name you like eg WebcamTutorial.

Next we are going to build our custom WebcamPanel component. Make some new "actionscript class" in your project by choosing File > new >actionscript class. As package we choose myComponents and we call our class WebcamPanel. As superclass we choose mx.containers.Panel.

We want to have all the functionality from our parent class so in the constructor of our WebcamPanel class we call the super() method.

public function WebcamPanel(){
   super();
   insertWebcamVideo();
}

As you see in the constructor we also calling another method called insertWebcamVideo(). These method looks like this:

public function insertWebcamVideo():void{
   var videoHolder:UIComponent = new UIComponent();
   var camera:Camera = Camera.getCamera();
   video = new Video(camera.width*2, camera.height*2);
   video.attachCamera(camera);
   videoHolder.addChild(video);
   addChild(videoHolder);
   videoHolder.y =10;
}

The first thing we do in the insertWebcamVideo method is declaring a variable videoHolder of the UIComponent type. We must do this to avoid getting errors when adding this as a child to our Panel. I tried casting to an UIComponent also but this way seems to be the only working. The next step is to put our camera stream into a Video object by using the attachCamera method. Next we want to make this all visible (= put it in the DisplayList) by using the addChild method. This way we first put our video object in the videoHolder and last but not least we put our videoHolder in the Panel which we are inheriting from. In the example code above we also changed the y value of our videoHolder to make it look a bit better in the Panel.

Ok, now we have following actionscript class:

package myComponents
{
 import mx.containers.Panel;
 import flash.media.Camera;
    import flash.media.Video;
    import mx.core.UIComponent;   

public class WebcamPanel extends Panel
 {
  public var video:Video
  public function WebcamPanel(){
   super();
   insertWebcamVideo();
  }
  public function insertWebcamVideo():void{
   var videoHolder:UIComponent = new UIComponent();
   var camera:Camera = Camera.getCamera();
   video = new Video(camera.width*2, camera.height*2);
         video.attachCamera(camera);
         videoHolder.addChild(video);
         addChild(videoHolder);
         videoHolder.y =10;
  }
 }
}

Next step in our webcam project is to use our actionscript component in a mxml application.

Choose FILE > new > MXML application. Give it eg the name "MainApplication".

Your MainApplication.mxml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">    

</mx:Application>

You can see we are now using the default adobe namespace defined by mx prefix.
But we also want to use our own namespace where our components are defined. Change the application opening tag so it looks like this:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:MyComp="myComponents.*" layout="absolute">

As you can see we can now reference all our own components in the package myComponents with a prefix "MyComp".
This is really cool ! So lets implement our component in our application and skin our panel (YEAH, skinning is sooo damn easy in Flex !) Type following code right under your <mx application> opening tag:

<MyComp:WebcamPanel x="69" y="51" width="360" height="320" layout="absolute" backgroundColor="#ffffff" backgroundAlpha="1.0" title="Thats me…" fontSize="18" fontFamily="Verdana" color="#ff0080" borderColor="#ff0080" borderStyle="solid" cornerRadius="0" barColor="#FFFFFF" borderThickness="10" dropShadowColor="#FFFFFF" dropShadowEnabled="false" footerColors="#FFFFFF" headerColors="#FFFFFF" highlightAlphas="0" shadowDirection="center" textAlign="right" textDecoration="none" borderAlpha="0" fontWeight="bold" id="pnlWebcam" shadowDistance="10" alpha="1.0" >
</MyComp:WebcamPanel>

This is the code that places our own WebcamPanel on the screen. You see we use our own MyComp namespace to reference our component. Next we want to place a normal Panel where we are going to place the snapshot later on :

<mx:Panel x="499" y="51" width="360" height="320" layout="absolute" backgroundColor="#ffffff" backgroundAlpha="1.0" title="Thats me also..." fontSize="18" fontFamily="Verdana" color="#ff0080" borderColor="#ff0080" borderStyle="solid" cornerRadius="0" barColor="#FFFFFF" borderThickness="10" dropShadowColor="#FFFFFF" dropShadowEnabled="false" footerColors="#FFFFFF" headerColors="#FFFFFF" highlightAlphas="0" shadowDirection="right" textAlign="left" textDecoration="none" borderAlpha="0" fontWeight="bold" id="pnlSnapshot" visible="false">
</mx:Panel>

We also place a button instance on the screen by writing following code:

<mx:Button x="288" y="389" label="Take Snapshot" borderColor="#FFFFFF" focusAlpha="1" color="#000000" textRollOverColor="#FFFFFF" textSelectedColor="#000000" themeColor="#ff0080" fillAlphas="[1.0, 1.0]" errorColor="#ff0080" fillColors="[#ff0080, #ff0080]" fontSize="14" fontFamily="Verdana" fontWeight="bold" cornerRadius="0" alpha="1.0" click="takeSnapshot()"/>

As you can see at then end of last code we call a function takeSnapshot() when a user click on the button. So next we have to do is writing that function that will do the snapshot job. We write this function in actionscript between tags. These tags are placed directly under your application tag. As mxml files are based on the XML standard we have to use a CDATA section wherein we write our actionscript code. So the start situation is like this :

<mx:Script >
   <![CDATA[   

//write code here    ]]>
</mx:Script>

Place following code between your CDATA section:

import mx.core.UIComponent;
import flash.display.BitmapData;	   

public function takeSnapshot():void{
        var snapshotHolder:UIComponent = new UIComponent();
	var snapshot:BitmapData = new BitmapData(320, 240, true);
	var snapshotbitmap:Bitmap = new Bitmap(snapshot);
	snapshotHolder.y =10;
	snapshotHolder.addChild(snapshotbitmap);
	pnlSnapshot.addChild(snapshotHolder);
	snapshot.draw(pnlWebcam.video);
	pnlSnapshot.visible = true;
}

As you can see in the function takeSnapshot we use the same technics as in the beginning of this article. We start by declaring a Bitmapdata object with width 320px and height 240 px. We put the bitmapdata in a real Bitmap object. Normally we should try now to add this Bitmap as a child to the Panel pnlSnapshot but also here it is not possible to add it directly because of type problems. So we use a snahshotHolder to store our bitmap. That snapshotHolder can easily be added to our pnlSnapshot as a child. After or before (you can choose) we did that we can call the draw() method of the BitmapData class to put the captured data in our bitmapData object (snapshot) and the job is done !

I hope you liked this tutorial and feel free to give some feedback :-)

Take a webcam snapshot in Flex 2.0

28 Responses to “Take a webcam snapshot in Flex 2.0”

  1. brilliant! you the man!!

  2. This is really nice.

    Is there a way to allow a user to SAVE the snapshop? I do not get a “send to server” option.

    Thanks

  3. Hey Banta, that picture above was made with a more complex example I am experiencing with. But It just run through the pixels, compresses them and send them to a PHP page where the image is saved to the server. It still has some bugs so I decided to not put it online already, but I am working on it ! Hold on…
    greetz,
    Koen

  4. Maybe a basic question, but how can I dynamicly add more instances of a snapshot on the stage?
    So when someone presses the ‘take snapshot’ button, a new instance of pnlSnapshot is added to the stage.

    Nice work with the tutorial, really raised my interested in Flex :-)

  5. Could you please show an example of how to send the webcam bitmap to the server as a jpg image ?

    This way it can be used as an webcam script. Thanks!

  6. Hi, I’ve checked your post, there is only a small chang in your code to work on Adobe Flex 2:
    video = new Video(camera.width*2, camera.height*2);

    Must be:
    var video:Video = new Video(camera.width*2, camera.height*2);

    Regards,

  7. This is a great tutorial and i absolutely love it. However, I do have one minor mild little complaint, if possible could you post the full application either the source in an rar, or just the application as you did with the class. Originally i had problesm doing it because I would screw up the application. Thanks.

    PS I really did love this tutorial it was amazing

  8. That’s great for snapshot a pic. but, how about video stream from a client that monitored by the server. i’m looking for this app. did u have a sample ? please PM me. i’d be glad to receive your mail.

    Best Regards
    sutuy

  9. Yes I would love to know if anyone has figured out how to stream the data instead of just snapshots…

    Please send me an email if you have or post a comment here.

    Regards

    Mark

  10. [...]  http://newmovieclip.wordpress.com/2006/05/26/take-a-webcam-snapshot-in-flex-20-beta-3/ [...]

  11. Hi,
    Thanx for the tutorial, it was great to have it. I am a newbie to flex and wanted to have the capability to save an image taken right from webcam to the server. this code allowed me to do this. thanx a lot.

    Regards
    Tiklu

  12. Nice tutorial…and recently I found this on image saving: http://www.kaourantin.net/archive/2005_10_01_flashgraphics_archive.html
    http://blog.webqem.com.au/index.php/2006/09/08/flex-20-image-saving/

  13.  

  14. Hi!

    Is it possible for you to mail this project? Have you figured out how to save the snapshots to a server?

    Kind regards,
    Martin

  15. [...] apps out there but not alot that relate to webcams as such. I did find a good one which deals with flex and webcams which helped me alot. In anycase lets get to this basic webcam app… I’ve gotta warn you, this [...]

  16. Hi, great tuto, if you want save your bitmap on a server, first you have to compress it (Flex provides a PNG and JPG compressor classes) then send it (using Remote Object is better but you can just use URLRequest()) see my blog :

    http://thomasdecaux.zeblog.com

    hope help someone !

  17. good code , working here
    how to use streaming with camera are not explain

  18. Oh, and did not know about it. Thanks for the information …

  19. Great.. i newby in flex… please send my your sample project…
    Regards

    Kris

  20. Really Super, it’s Working.

    Thank U So Much.

  21. Your example and tutorial has been a very very useful starting point. I have moved the controls out to javascript, removed your webcam contained, inserted some choosing in the file upload name, set resize parameters to fit to windows, and rewritten some other tricks. Next I will implement “data:” in order to allow for serverless work.

    In my website here linked I am releasing an small service if people just needs to take quick snapshots, no flex learning.

    If someone needs the source code, I think that I can email it under mozilla license terms. Check the website.

  22. But I thought there was no britney spears forgot panties my new news jessica simpson would reopen my cock, that would concentrate incest! Tony went to one daily porn sex and filmed my peasants above me.

  23. hi,
    Really super,
    but i want to create the same thing with flash.
    will it be possible? please help me out.

  24. its the best post from you, thanks a lot

  25. it is very useful, thanks a lot…
    http://www.syria-soft.net

  26. Hi.

    I’ve been searching for this kind of application all over the web. I have never used Flex before, but I tried to follow your tutorial in flex3, its very good. But I get errors when I try to build.

    Is there any chance that any of you who got this working could email it to phtwang@hotmail.com ? I would appreciate it VERY much.
    I really need to solve this before a expo in 2 weeks.

  27. Very interesting information! Thanks!

  28. Thanx this helped me a lot and lucky me that have a brand new webcam :)

Leave a Reply