Capture webcam success! Now how to make it repeat itself??

I have a code which captures my webcam and saves (and displays) a jpg image.
However, I want to make it so my code captures my webcam once every second or so.
Wait one second ---> Capture image -----> save (replace) over the previous image ------> do it again...
My current code is as follows:
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.protocol.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
public class camagain extends Panel implements ActionListener
     public static Player player;
     public CaptureDeviceInfo DI;
     public MediaLocator ML;
     public JButton CAPTURE;
     public Buffer BUF;
     public Image img;
     public VideoFormat VF;
     public BufferToImage BtoI;
     public ImagePanel imgpanel;
     public camagain()
          setLayout(new BorderLayout());
          setSize(320,550);
          imgpanel = new ImagePanel();
          CAPTURE = new JButton("Capture");
          CAPTURE.addActionListener(this);
          String str1 = "vfw:Logitech USB Video Camera:0";
          String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
          DI = CaptureDeviceManager.getDevice(str2);
          ML = new MediaLocator("vfw://0");
          try
               player = Manager.createRealizedPlayer(ML);
               player.start();
               Component comp;
               if( (comp = player.getVisualComponent()) != null )
                    add(comp,BorderLayout.NORTH);
               add(CAPTURE,BorderLayout.CENTER);
               add(imgpanel,BorderLayout.SOUTH);
          catch (Exception e)
               e.printStackTrace();
     public static void main(String[] args)
          Frame f = new Frame("SwingCapture");
          SwingCapture cf = new SwingCapture();
          f.addWindowListener(new WindowAdapter()
               public void windowClosing(WindowEvent e)
                    playerclose();
                    System.exit(0);
          f.add("Center",cf);
          f.pack();
          f.setSize(new Dimension(320,550));
          f.setVisible(true);
     public static void playerclose()
          player.close();
          player.deallocate();
     public void actionPerformed(ActionEvent e)
          JComponent c = (JComponent) e.getSource();
          if(c == CAPTURE)
               // Grab a frame
               FrameGrabbingControl fgc = (FrameGrabbingControl)
               player.getControl("javax.media.control.FrameGrabbingControl");
               BUF = fgc.grabFrame();
               // Convert it to an image
               BtoI = new BufferToImage((VideoFormat)BUF.getFormat());
               img = BtoI.createImage(BUF);
               // show the image
               imgpanel.setImage(img);
               // save image
               saveJPG(img,"c:\\test.jpg");
     class ImagePanel extends Panel
          public Image myimg = null;
          public ImagePanel()
               setLayout(null);
               setSize(320,240);
          public void setImage(Image img)
               this.myimg = img;
               //repaint();
          public void paint(Graphics g)
               g.drawImage(myimg, 0, 0, this);
     public static void saveJPG(Image img, String s)
          BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
          Graphics2D g2 = bi.createGraphics();
          g2.drawImage(img, null, null);
          FileOutputStream out = null;
          try
               out = new FileOutputStream(s);
          catch (java.io.FileNotFoundException io)
               System.out.println("File Not Found");
          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
          JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
          param.setQuality(0.5f,false);
          encoder.setJPEGEncodeParam(param);
          try
               encoder.encode(bi);
               out.close();
          catch (java.io.IOException io)
               System.out.println("IOException");
}Please help me.

import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.protocol.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;
public class camagain extends Panel implements ActionListener {
    public static Player player;
    public CaptureDeviceInfo DI;
    public MediaLocator ML;
    public JButton CAPTURE;
    public Buffer BUF;
    public Image img;
    public VideoFormat VF;
    public BufferToImage BtoI;
    public ImagePanel imgpanel;
    public javax.swing.Timer timer = new javax.swing.Timer(200, this); // 200ms is too fast increase it to suit your need
    public camagain() {
        setLayout(new BorderLayout());
        setSize(320, 550);
        imgpanel = new ImagePanel();
        CAPTURE = new JButton("Capture");
        CAPTURE.addActionListener(this);
        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        DI = CaptureDeviceManager.getDevice(str2);
        ML = new MediaLocator("vfw://0");
        try {
            player = Manager.createRealizedPlayer(ML);
            player.start();
            Component comp;
            if ((comp = player.getVisualComponent()) != null) {
                add(comp, BorderLayout.NORTH);
            add(CAPTURE, BorderLayout.CENTER);
            add(imgpanel, BorderLayout.SOUTH);
            Thread.sleep(5000);     // this is important, otherwise you may get NPE somewhere, needs polishing ;-)
            timer.start();                // start timer
        } catch (Exception e) {
            e.printStackTrace();
    public static void main(String[] args) {
        Frame f = new Frame("SwingCapture");
        camagain cf = new camagain();   // I didn't had 'SwingCapture, so I added camgain.....
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                playerclose();
                System.exit(0);
        f.add("Center", cf);
        f.pack();
        f.setSize(new Dimension(320, 550));
        f.setVisible(true);
    public static void playerclose() {
        player.close();
        player.deallocate();
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JComponent) {
            JComponent c = (JComponent) e.getSource();
            if (c == CAPTURE) {
                action();  // maoved every thing to new method action()
        } else if (e.getSource() instanceof javax.swing.Timer) {
            action();       // timer event , call action() again
    public void action() {    // your action handler code.....
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
        BUF = fgc.grabFrame();
        // Convert it to an image
        BtoI = new BufferToImage((VideoFormat) BUF.getFormat());
        img = BtoI.createImage(BUF);
        // show the image
        imgpanel.setImage(img);
        // save image
        saveJPG(img, "d:\\test.jpg");
    class ImagePanel extends Panel {
        public Image myimg = null;
        public ImagePanel() {
            setLayout(null);
            setSize(320, 240);
        public void setImage(Image img) {
            this.myimg = img;
            repaint();
        public void paint(Graphics g) {
            super.paint(g);
            g.drawImage(myimg, 0, 0, this);
    public static void saveJPG(Image img, String s) {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(s);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f, false);
        encoder.setJPEGEncodeParam(param);
        try {
            encoder.encode(bi);
            out.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
}

Similar Messages

  • How to make a repeated todo

    Does anyone know how to make a repeated to do like ...balance checkbook and have it repeat every three or for days...
    also is there a way to have an alarm be a text message sent to my phone...cool no?
    imac G5   Mac OS X (10.4.7)  

    I'm using GarageBand on a iPad mini 2

  • How to make horizantal repeating table?

    Hi All,
    I just want to make horizantal repeating table in InfoPath form. In brief, if insert new item in repeating table it should add next to first table not one by one.
    How to achieve this, thanks in advance!

    Hello,
    It should work in IP 2013 as well. Also make sure that you are designing client form because it does not works in browser based form.
    http://www.bizsupportonline.net/infopath2013/videos/infopath-2013-show-hide-columns-horizontal-repeating-table.htm
    Hemendra:Yesterday is just a memory,Tomorrow we may never see
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

  • Editing complete, now how to make a DVD with menu

    This is my first go through with PP CS4 and I'm nearly complete. I've edited my entire video and I've organized my project into about 40 sequences. Now I'd like to create a DVD menu for it and export the entire project to DVD (likely more than one since it totals nearly 4 hours). I'm looking to create a looping video at the menu with a couple options like "play all", "scene selection", and "bonus features". Each of my sequences is a different scene. What is my next step, what program(s) do I use from here to make this happen? After reading some other threads it looks like Encore is the direction I need to head in, but since this is my first time, I'm unfamiliar at the moment.
    Any tips and/or suggestions would be helpful. Thanks.
    Ben

    http://tv.adobe.com/show/learn-encore-cs4/

  • Erased unwanted parts of photo now how to make a background

    I am just getting started with PSE 8.0.1. I have a photo where I just want that part which is a given person.  I cropped then erased unwanted parts. The erased areas are pure white.  How would I create a background that looked like clouds or draped cloth or something that would appear only in the erased parts of the photo?

    Sorry to say, but the work flow which you describe will not give you result which you desire.
    Go to File>new>blank file. Enter height and width, and resolution. The resolution should be about the same as that of your picture
    Set the foreground and background color chips (lower left) to diffent colors - for example shades of light blue
    Go to Filter>render>clouds. You should have a background with a cloud pattern
    Minimize this as you wil need it subsequently
    Make a selection of the person which you wish to retain, using one of the selection tools - e.g. the Selection brush tool. After you make the selection, you will see "marching ants" around the selection.
    Go to Select>inverse, then hit delete on the keyboard, go to select>inverse. The checkered pattern denotes transparency
    Go to Edit>copy. This will place the selection on the clipboard.
    Go back to cloud background, go to Edit>paste. This will put your selection on a new layer
    Access the move tool to position and resize the selection over the background.
    Merge down

  • How to make multiple repeating pages for XML child nodes

    I have a schema that has many levels, and I am trying to have some of the child data print on separate pages.
    <As>
    <A id=1>
    <Bs>
    <B id=1 name="B1">
    <Cs>
    <C id=1 name="B1C1" />
    <C id=2 name="B1C2" />
    <C id=3 name="B1C3" />
    </Cs>
    </B>
    <B id=2 name="B2">
    <Cs>
    <C id=1 name="B2C1" />
    <C id=2 name="B2C2" />
    <C id=3 name="B2C3" />
    </Cs>
    </B>
    <Bs>
    </A>
    <As>
    I want to place the data from A and B on page 1 (A is header fields and B is a table showing B1, B2 etc), and then per B, place data from C items on their own pages (repeat as necessary).
    So the page output would be:
    Page 1
    A:1 (header items)
    B table
    B1
    B2
    Page 2
    A:1 (header items)
    B id: 1
    C data for B1C1
    Page 3
    A:1 (header items)
    B id: 1
    C data for B1C2
    Page 4
    A:1 (header items)
    B id: 1
    C data for B1C3
    Page 5
    A:1 (header items)
    B id: 2
    C data for B2C1
    Page 6
    A:1 (header items)
    B id: 2
    C data for B2C2
    Page 7
    A:1 (header items)
    B id: 2
    C data for B2C3
    Page 8
    A:2 (header items)
    etc.
    I am hoping that with this quick sketch someone can tell me how to accomplish the placement of the C items.

    For the time being, I can only respond to Pages for iOS. OS X I'll need to check when I get home (or perhaps someone else will beat me to it). You may wish to post in the Pages for Mac forum for better exposure.
    In Pages for iOS you are limited to a single header and footer. There is no Section structure so no way to do different headers/Footers for different pages (as you can do in MS word for example). To modify the Header and insert the text you want: Tap the Tools icon (wrench in upper right), then Document Set up. Tap in the header field, then tap and hold to use the menu to insert pages numbers, then type the text you need.
    Quite possibly. Check the app store. Or you may be able to set this up in Pages for OS X and import it into Pages on the iPad. I'm not certain the sections will import however.
    Also consider using a different app, such as word for iOS or any of the numerous other word processing apps available.

  • How to make terminal repeat sentences

    In the terminal application, I use the "echo" command line a lot to get Terminal to repeat sentences that I input. I was wondering if it is possible to make the "Echo" command automatially repeat pre-set sentences. For example, I want Terminal to say "Good Morning" in the morning and "Good Night" at night. Is this possible? Thnaks in advance.

    You question is vague so giving a specific solution is difficult.
    What times exactly do you want the commands to run? Why do you need to do this in the Terminal?
    The absolute easiest way to do this is to use Automator and create a calendar event. Have the workflow run a shell or Applescript that speaks the sentence you want.
    For example
    then schedule this to run when you want it to. Same for Good Night.
    Thee are many other ways to schedule a job to run under OS X but launchd (see man page) is the prefered way but likely overkill for what you are asking.

  • How to make a repeating section by clicking on a 'button'

    Hello,
    I am creating a form and there is a secion for 'Add a Dependent'.  The form only show enough fields for one dependent.  I have created a button that says 'Add a Dependent'. When the user clicks on this button I would like the section to show up again, asking for the information for the new dependent. Also, there will be a cancel button so that if they click on 'add a dependent' too many times, they can cancel each one individually if needed.The purpose for this is because it will take up much less space in the form. Can anyone help?
    Thank you in advance,
    Nik

    Here is what I did for making the Subform repeat..
    Selected the Dependants subform and went to the Binding tab, checked the cehckbox "Repeat Subform each Data Item"..
    Placed the below code in the click event of the Add Dependant button.
         Dependants.instanceManager.addInstance(1);
    Placed the below code in the Click event of the "X" button:
              if 
    (this.parent.index>0)
              Registration.content.Dependants.instanceManager.removeInstance(this.parent.index);
    Placed the below code in the Initialize event of the "X" button:
         if(this.parent.index==0)
              this.presence = "hidden";
    Let me know if you have any issues..
    Thanks
    Srini

  • How to make a diagonal split screen in CS3

    Dear Folks,
    Any body now how to make a digonal split screen in permiere pro CS3?
    A normal split screen is ok like two videos side by side.
    Regards,
    TP

    This is an example of what Bill is saying...give him credit...  I just illustrated...photoshop files for the mattes...pure white and pure black...
    ps..if you dont want such a sharp line between the screens you can select the matte area in photoshop and "feather" the selection a few pixels...

  • How to make Default ALV layout

    Hi,
    I want to make 'STANDARD view' as a default ALV Layout...If anybody execute my ALV Report STARD Layout variant should display by default. Other variant layouts they can select from drill down..
    I know class and method but i don't know how to write code for this with paremeters..Can anybody help on code please..
    CLASS : CL_SALV_WD_C_TABLE
    METHOD : IF_SALV_WD_COMP_TABLE_PERS~SET_STANDARD_VIEW
    My current ALV CODE
      DATA: l_ref_interfacecontroller TYPE REF TO iwci_salv_wd_table .
      DATA: l_value TYPE REF TO cl_salv_wd_config_table.
      l_ref_interfacecontroller = wd_this->wd_cpifc_alv( ).
      l_value = l_ref_interfacecontroller->get_model( ).
    Thanks.,
    Subba

    Hi sarbjeet singh,
    Thanks for your reply...
    I didn't understand your answer...Already this view gone to production system and every USER created his own view..
    Now how can make default standard view to all users..
    If i keep Standard view as Intial view and release transport to production is it effected to all users and display standard view as initial view?
    Thanks,
    Subba

  • How to make a curve dotted line

    Hi there,
    Since now 2 days I am trying to figure out how to make a curve dotted line with photoshop CS3 on WinXP. I know how to make a strait line using the line tool.
    Now, how to make a curve line ? I tried the pen tool, but it ended up with a filled shape rather than with a curve line
    How to set the thickness of this curve ?
    How to make a dotted curve ?
    Of course, I don't want to use hand-drawings with the brush.
    Thanks a lot for your help,
    Alex_pier

    Used the Pen tool, but click on the correct icon on the top left on the Options Bar. That way you can get a Path instead of a Shape Layer.
    Once you have your Path you can stroke it with a Brush or any drawing tool. Various options appear in the Brushes palette. For a dotted line you will need to increase the spacing. If you want dashes, use a square brush and set the Angle Jitter to Direction.

  • How to make barcode interface with SAP B1

    Hi all,
               I need an interface code to make an interface between barcode printer with SAP B1. i got a scenario from the barcode people. that they are using EPL coding only for Barcode printer print, there they need to run this EPL code in Dos mode, for that .bat file is needed. hope you might got some idea that how a barcode printer is working. now how to make an interface of SAP B1 with Barcode printer.
    how to generate a code which will put the bar code and price with the AP invoice of the item in EPL code which is in a text format. so that by .bat format txt file should be run in dos mode.
    if you have any other process to run the EPL code, kindly send me the details as soon as possible....its very urgent.
    regards
    sandip

    Sandip,
    I think what you may be more concerned about, rather than the printer "language" (ZPL, EPL, etc...) is the symbology that you require for barcodes. Like 3of9, code 128, etc.
    The standard B1 PLD will input a barcode image for whatever field you specify, but only in a couple of symbologies. The Advanced Layout Designer apparently supports a lot more. I have read that it may be requested from you partner, or if on 2007, it is part of the standard install.
    B1 should pass the bar code to the printer, where the printer's language will decode and print it out. Bypass the .bat file, bypass DOS, let B1 do it.
    Is your Epson printer supported under Windows?

  • How to make executable file in labview.

    HI All,
    I have labview student edition V14 (2014),
    I want my vi to be an executable file.
    i searched in google but in  my vi project  its showing only  build specefication->new->source distrubtion.
    i dont have Application , now how to make an executable file.
    Regards
    Punith

    You need the Professional version to make an executable.  You could also buy the App Builder seperately.  I don't remember the price at the top of my head.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Calendar event - how to make it to repeat it self?

    Hi,
    I was surprised to say that I added a calendar event and I can't make to repeat itself.
    For example, I'm using this because I have to take some medicine every day in the morning and I always use reminder for this, to be sure that I take it So it is not a event reminder, which I would like o repeat itself.
    I didn't found anything for this setting. Did anyone find such a thing?
    Thank you.
    Br,
    Qqcsi

    Hi,
    You are right, I forgot to include the model of my phone. Sorry. It is a Nokia N79.
    Unfortunetly I don't have what you suggested
    Even my Nokia 6100 had it. It's strange that in the N79 I can't find it
    Thanks,
    Qqcsi

  • How to make it capture at 640x480

    Hi guys. I just got an external iSight and haven't figured out how to make it capture in QT pro 7 at 640x480. It's only doing it at 320x200. Any hints? Thanks!

     You are welcome. If you have all the info you need, please mark your question "Answered".
    ... choose 640x480 in iChat ...Are you SURE you want to pay for even more broadband speed and processor power in order to send larger video chat transmissions?
    Check your Broadband Speed. If you do not have adequate video quality now, you can increase your iChat video image quality if you and all your video chat buddies can buy more bandwidth from your ISP (or, if not, find a faster ISP.)
    I recently have upgraded to 9 Megs down and 1 Meg up, thus doubling my previous bandwidth. The increased speed significantly improves multi-party video quality, especially in videos with other users who have similarly speeds.
    Cheers,
    EZ Jim

Maybe you are looking for