简体   繁体   English

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

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

I am creating one GUI application in swing Java.I have to integrate web cam with my GUI. 我正在使用swing Java创建一个GUI应用程序。我必须将web cam与我的GUI集成。 Any body have idea about this ? 有没有人对此有所了解?

  1. Download and install JMF 下载并安装JMF
  2. Add jmf.jar to your project libraries 将jmf.jar添加到项目库中
  3. Download the FrameGrabber source file and add it to your project 下载FrameGrabber源文件并将其添加到您的项目中
  4. Use it as follows to start capturing video. 使用它如下开始捕获视频。

    new FrameGrabber().start(); 新的FrameGrabber()。start();

To get to the underlying image, you simply call getBufferedImage() on your FrameGrabber reference. 要获取基础图像,只需在FrameGrabber参考上调用getBufferedImage()即可。 You can do this in a Timer task for example, every 33 milliseconds. 您可以在Timer任务中执行此操作,例如,每33毫秒。

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

Freedom for Media in Java is an alternative implementation of JMF (API compatible). Java中的Freedom for Media是JMF(API兼容)的替代实现。 Just in case you'd like to use OpenSource library. 以防万一你想使用OpenSource库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM