使用webcam-capture替換JMF調用攝像頭
最近有個需要通過java調用攝像頭,並截圖的需求,在網上找了下資料,大部分是用一個叫jmf的庫,但是jmf已經幾百年沒有更新,用起來各種問題。后來又找了個叫fmj的庫,說是jmf的替代品,但是資料太少,不知道怎么下手。
又在網上找了下搜索找到了一個開源項目webcam-capture,真心不錯。基本的示例比較齊全,上手快。
webcam-capture項目地址: https://github.com/sarxos/webcam-capture
使用webcam-capture寫了個截圖的小demo,代碼如下:
public class CaptureDemo { private static int num = 0; public static void main(String[] args) throws IOException { final Webcam webcam = Webcam.getDefault(); webcam.setViewSize(WebcamResolution.VGA.getSize()); WebcamPanel panel = new WebcamPanel(webcam); panel.setFPSDisplayed(true); panel.setDisplayDebugInfo(true); panel.setImageSizeDisplayed(true); panel.setMirrored(true); final JFrame window = new JFrame("攝像頭"); window.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { webcam.close(); window.dispose(); } }); // window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JButton button = new JButton("截圖"); window.add(panel, BorderLayout.CENTER); window.add(button, BorderLayout.SOUTH); window.setResizable(true); window.pack(); window.setVisible(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { button.setEnabled(false); String fileName = "D://" + num; WebcamUtils.capture(webcam, fileName, ImageUtils.FORMAT_PNG); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(null, "截圖成功"); button.setEnabled(true); num++; return; } }); } }); } }