8

I am creating one GUI application in swing Java.I have to integrate web cam with my GUI. Any body have idea about this ?

om.
  • 4,159
  • 11
  • 37
  • 36

2 Answers2

8
  1. Download and install JMF
  2. Add jmf.jar to your project libraries
  3. Download the FrameGrabber source file and add it to your project
  4. Use it as follows to start capturing video.

    new FrameGrabber().start();

To get to the underlying image, you simply call getBufferedImage() on your FrameGrabber reference. You can do this in a Timer task for example, every 33 milliseconds.

Sample code:

public class TestWebcam extends JFrame {
  private FrameGrabber vision;
  private BufferedImage image;
  private VideoPanel videoPanel = new VideoPanel();
  private JButton jbtCapture = new JButton("Show Video");
  private Timer timer = new Timer();

  public TestWebcam() {
    JPanel jpButton = new JPanel();
    jpButton.setLayout(new FlowLayout());
    jpButton.add(jbtCapture);

    setLayout(new BorderLayout());
    add(videoPanel, BorderLayout.CENTER);
    add(jpButton, BorderLayout.SOUTH);
    setVisible(true);

    jbtCapture.addActionListener(
       new ActionListener() {
          public void actionPerformed(ActionEvent e) {
               timer.schedule(new ImageTimerTask(), 1000, 33);
          }
       }
   );
  }

  class ImageTimerTask extends TimerTask {
     public void run() {  
         videoPanel.showImage();
     }
  }

  class VideoPanel extends JPanel {
      public VideoPanel() {
        try {
            vision = new FrameGrabber();
            vision.start();
        } catch (FrameGrabberException fge) {
        }
      }

      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null)
           g.drawImage(image, 10, 10, 160, 120, null);
      }

      public void showImage() {
          image = vision.getBufferedImage();
          repaint();   
      }
  }

  public static void main(String[] args) {
        TestWebcam frame = new TestWebcam();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(190, 210);
        frame.setVisible(true);
  }
}
JRL
  • 76,767
  • 18
  • 98
  • 146
  • Thanks JRL , I am trying to implement it,I want to known whether it will automatically detect my webcam ? – om. Sep 05 '09 at 10:39
2

Freedom for Media in Java is an alternative implementation of JMF (API compatible). Just in case you'd like to use OpenSource library.

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68