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

Advertisements

67 responses to “Take a webcam snapshot in Flex 2.0

  1. chris 4 June , 2006 at 5:09 pm

    brilliant! you the man!!

  2. Banta 5 June , 2006 at 12:20 am

    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. Koen 5 June , 2006 at 7:48 am

    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. Alwyn 28 June , 2006 at 6:57 pm

    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. Dutchguy 5 July , 2006 at 1:58 pm

    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. Daniel Guerrero 28 July , 2006 at 5:14 pm

    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. Ben 8 December , 2006 at 3:09 am

    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. sutuy 1 March , 2007 at 9:52 am

    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. Mark 13 March , 2007 at 5:49 pm

    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. Pingback: Wabbit » Blog Archive » Apollo Webcam App

  11. Tiklu Ganguly 27 April , 2007 at 3:51 pm

    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. Martin 24 August , 2007 at 4:28 am

    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

  13. Pingback: BJW » Flex and the webcam - Net Perspective Blog by Brendon Wildbore

  14. Tom 21 September , 2007 at 12:46 am

    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 !

  15. abhishek 18 October , 2007 at 7:53 am

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

  16. Andy 19 December , 2007 at 6:07 pm

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

  17. Kristal 20 December , 2007 at 3:23 pm

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

    Kris

  18. arumugam 12 January , 2008 at 2:28 pm

    Really Super, it’s Working.

    Thank U So Much.

  19. Alejandro Rivero 27 January , 2008 at 8:10 pm

    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.

  20. pibejexia 24 February , 2008 at 3:55 pm

    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.

  21. Angelina 27 February , 2008 at 1:43 pm

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

  22. SamaraRegion 29 February , 2008 at 7:58 pm

    its the best post from you, thanks a lot

  23. cgcollection 5 March , 2008 at 12:06 pm

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

  24. Mattias 4 April , 2008 at 10:56 am

    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.

  25. moonstudio 23 April , 2008 at 9:01 am

    Very interesting information! Thanks!

  26. Webcam 18 May , 2008 at 6:29 pm

    Thanx this helped me a lot and lucky me that have a brand new webcam 🙂

  27. biyified 10 July , 2008 at 7:09 pm

    thanx man, thats cool, i dint even use flex, i used flash and it works.

  28. Tonydep 14 July , 2008 at 4:08 pm

    Great tutorial!
    I would ask you if you know any tutorial for doing the same thing in flash cs3
    Thanks a lot
    Tonydep

  29. hendrix 20 August , 2008 at 5:04 am

    Thanks for the example. This is just what I was looking for. I have a kegerator in my basement and a Flex app that monitors the temp and amount of beer left and talks to you when you pour a beer. Now I will have it take a snapshot via the web cam also!

  30. рукОДелие 21 October , 2008 at 8:51 am

    Thanks, very interesting

    ____
    oo / / \ \
    (_, \ / \ _ / \
    \ \ _/ _ \ _/ >
    /_ /подарки \ _\

  31. Pingback: Webcam snapshots with Flex3

  32. Jakester 26 October , 2008 at 8:31 pm

    How do you insert this into a regular webpage on a server so someone can access it and look at their webcam?

  33. Luis 18 November , 2008 at 8:19 pm

    Hi guys, someone knows how to turn off the camera when a take the picture ?

  34. Егор 3 December , 2008 at 5:27 pm

    Братцы, о чем вы пишете? ? При чем тут этот пост? ?

  35. Веталь 4 December , 2008 at 5:43 pm

    Как можно читать этот блог с мобильника? Что нужно скачать?

  36. desingz 12 December , 2008 at 3:12 am

    @Luis i guess just removing the panel will detach the webcam …

  37. aviraj 12 December , 2008 at 8:59 am

    hi,guys I think about it. this is very good picture.

    jhon

  38. Laurent 30 March , 2009 at 10:58 pm

    Hi,
    Thanks for this tutorial so nice.
    Just, at first i d test it on apple (imac and isight) and doesn’t work. Why ?
    On pc works fine !

    How do you do for save it on a base ? or for save the pictures?

  39. Webcam motion detection 2 April , 2009 at 4:16 am

    Here is a decent list of motion detection links for c# and flash developers – http://www.ugolog.com/pages/webcam-motion-detection-for-flash-flex-and-csharp

  40. rusonlineinvest 21 April , 2009 at 1:33 am

    Слышал продолжение телепузиков снимают

  41. catalellHiz 25 May , 2009 at 11:39 pm

    Позновательно!!!!

  42. amar 22 July , 2009 at 10:48 am

    hey all
    im a newbie
    im in my intern now
    i was asked to make an application which integrate facebook and webcam(which can view and take picture)
    help anyone please
    and thanks in advance

  43. keval 26 November , 2009 at 6:39 am

    Thanks, useful material. Has added your blog in bookmarks.

  44. Surat Pyari 3 December , 2009 at 12:32 pm

    Thanks, very useful for me.

  45. livejasmin 13 January , 2010 at 5:27 pm

    nice share you have here, keep up the good work !

  46. John 21 January , 2010 at 9:29 pm

    I really did love this tutorial it was amazing

  47. Loshd 19 May , 2010 at 7:28 pm

    A few stragglers, and before that!

  48. patrick 19 June , 2010 at 1:20 am

    Free live adult Webcams
    Sexy live girls free chat
    the best quality live sex
    http://www.needlivegirls.com

  49. Grand 18 July , 2010 at 6:55 pm

    Thanks for the helpful information

  50. Pingback: First Flex 2 App – Webcam motion tracking | Toby Tremayne

  51. Pritesh Desai 26 July , 2010 at 7:54 pm

    How can I flip the video feed right to left?

  52. Xstroy 30 July , 2010 at 1:30 pm

    Once I remember, too, there were similar questions.
    Come to visit us on Xstroy.com

  53. Rose 18 September , 2010 at 8:38 am

    Hey, I was reading your post and I just wanted to say thank you for putting out such great content. There is so much nonsense on the internet these days its difficult to find anything worthwhile. I showed this to my husband since this is the kind of thing he likes to read online. Thanks for the article and tips.

  54. Pingback: Take a webcam snapshot in Flex 2.0 | Marines UX DevStudio

  55. dude 5 March , 2011 at 2:53 pm

    hi,
    thx for the advice.

    1. programmatically adding video to stage:

    var videoContainer_:UIComponent = new UIComponent();
    videoContainer_.addChild(video);
    videoContainer.addChild(videoContainer_);

    2. as component
    Main.mxml

    CameraUIComponent.mxml

  56. flashuac 4 May , 2011 at 11:37 am

    Very interesting post! 🙂

  57. imalindatep 10 May , 2011 at 1:19 pm

    We pride ourselves in being able to bring you How -[url=http://cheapesthawaii.zapto.org/discount-mercaptopurine.html]discount mercaptopurine handbook[/url] .? pharmacology notes free – americas army medical training test answers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s