如何在 Java 中连接到网络摄像头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10696580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect to webcam in Java?
提问by Neha Raje
I have a form in which i want to capture the image of the person and display that image in the form.
我有一个表单,我想在其中捕获人的图像并在表单中显示该图像。
How can i connect to the webcam through java and display that image in the form?
如何通过 java 连接到网络摄像头并在表单中显示该图像?
回答by npinti
You could use JavaCVto capture the image.
您可以使用JavaCV来捕获图像。
This code should get you started (taken from here):
此代码应该可以帮助您入门(取自此处):
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.VideoInputFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class GrabberShow implements Runnable {
//final int INTERVAL=1000;///you may use interval
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public GrabberShow() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
@Override
public void run() {
FrameGrabber grabber = new VideoInputFrameGrabber(0);
int i=0;
try {
grabber.start();
IplImage img;
while (true) {
img = grabber.grab();
if (img != null) {
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
cvSaveImage((i++)+"-capture.jpg", img);
// show image on window
canvas.showImage(img);
}
//Thread.sleep(INTERVAL);
}
} catch (Exception e) {
}
}
}
Another alternative would be to use the Java Media Framework (JMF). You can find an example here.
回答by Bartosz Firyn
You can use Webcam Captureproject to do that. It's working on Windows XP, Vista, 7, Linux, Mac OS, Raspberry Pi and more. There is a ready-to-use Swing component extending JPanel which can be used to display image from your webcam. Please found this examplefor more details of how this can be done - it presents some advanced capabilities of this component, but basic usage would be the following:
您可以使用Webcam Capture项目来做到这一点。它适用于 Windows XP、Vista、7、Linux、Mac OS、Raspberry Pi 等。有一个扩展 JPanel 的即用型 Swing 组件,可用于显示来自网络摄像头的图像。请找到此示例以获取有关如何完成此操作的更多详细信息 - 它展示了该组件的一些高级功能,但基本用法如下:
JFrame window = new JFrame("Test webcam panel");
window.add(new WebcamPanel(Webcam.getDefault()));
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
After you run this code you should see JFrame with image from your webcam inside.
运行此代码后,您应该会在内部看到带有网络摄像头图像的 JFrame。
回答by sarath
Webcam.setAutoOpenMode(true);
BufferedImage image = Webcam.getDefault().getImage();
ImageIO.write(image, "PNG", new File("F:/test.png"));
can download the latest version from https://github.com/sarxos/webcam-capture
可以从https://github.com/sarxos/webcam-capture下载最新版本
and add other library file that in the zip file
并在 zip 文件中添加其他库文件