2009-09-05 81 views
6

我在swing中創建了一個GUI應用程序。我必須將web cam與我的GUI集成。任何機構都有這個想法?如何將Webcam整合到Java的Swing應用程序中?

+1

有Java的媒體框架。有了JMF,你可以播放電影,查看攝像頭,...也許是你的解決方案 – 2009-09-05 05:55:11

回答

7
  1. 下載並安裝JMF
  2. 添加jmf.jar到項目庫
  3. 下載FrameGrabber源文件並將其添加到您的項目
  4. 如下開始捕捉視頻使用它。

    new FrameGrabber()。start();

要獲得底層圖像,只需在FrameGrabber引用上調用getBufferedImage()。你可以在Timer任務中做到這一點,例如每33毫秒。

示例代碼:

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

謝謝JRL,我試圖實現它,我想知道它是否會自動檢測我的攝像頭? – 2009-09-05 10:39:35

相關問題