【问题标题】:How to integrate Webcam in Swing application of Java?如何在 Java 的 Swing 应用程序中集成 Webcam?
【发布时间】:2013-02-11 13:33:32
【问题描述】:

我正在用 Swing Java 创建一个 GUI 应用程序。我必须将网络摄像头与我的 GUI 集成。有没有人知道这个?

【问题讨论】:

  • 有Java媒体框架。使用 JMF,您可以播放电影、查看网络摄像头……也许这是适合您的解决方案

标签: java


【解决方案1】:
  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);
  }
}

【讨论】:

  • 谢谢JRL,我正在尝试实现它,我想知道它是否会自动检测我的网络摄像头?
【解决方案2】:

Freedom for Media in Java 是 JMF 的替代实现(API 兼容)。以防万一您想使用 OpenSource 库。

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 2010-11-23
    • 2012-01-12
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多