Java调用摄像头截图

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

 

posted @ 2015-06-26 14:34  永远改不完的bug  阅读(11679)  评论(1编辑  收藏  举报