How to integrate a webcam into a Java Swing application?

I am creating one GUI application in swing Java. I need to integrate a webcam with my GUI. Does any body have an idea about this?

+6
java
source share
2 answers
  • Download and install JMF
  • Add jmf.jar to project libraries
  • Download the source FrameGrabber file and add it to your project
  • Use it as follows to start capturing a video.

    new FrameGrabber (). start ();

To jump to the base image, you simply call getBufferedImage () based on the FrameGrabber link. You can do this in a timer task, for example, every 33 milliseconds.

Code example:

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); } } 
+7
source share

Media Freedom in Java is an alternative implementation of JMF (API compatible). Just in case, you would like to use the OpenSource library.

+2
source share

All Articles