簡體   English   中英

如何在Java的Swing應用程序中集成Webcam?

[英]How to integrate Webcam in Swing application of Java?

我正在使用swing Java創建一個GUI應用程序。我必須將web cam與我的GUI集成。 有沒有人對此有所了解?

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

    新的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);
  }
}

Java中的Freedom for Media是JMF(API兼容)的替代實現。 以防萬一你想使用OpenSource庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM