Webcam Capture
Webcam Capture 下载
https://github.com/sarxos/webcam-capture
Webcam Capture作用
1.获取电脑的摄像头
2.获取并摄像头返回的画面(每秒30张)
Webcam Capture使用方法
获取并打开默认摄像头
Webcam 类
Webcam webcam = Webcam.getDefault();//创建Webcam类对象
webcam.open();
注意,此时默认摄像头不能被其他程序占用(如视频会议程序),否则会报错
获取摄像头返回的画面
方法:getImage()
该方法可以返回摄像头画面,返回对象类型为 BufferedImage
BufferedImage bi = webcam.getImage();//获取图像并储存在bi中
//返回的图像可以在JFrame类对象上画出(涉及JFrame类使用)如下
JFrame jf = new JFrame();
Graphics g = jf.getGraphics();
g.drawImage(bi,x,y,Width,Height,null);
//也可以保存为图片文件(涉及File类使用)如下
ImageIO.write(webcam.getImage(), "PNG", new File("文件名字.png"));
在JFrame上输出视频
原理:在循环中将图片获取和输出
将一张张图片输出,就形成了视频
JFrame jf = new JFrame();
Graphics g = jf.getGraphics();
while(true){
BufferedImage bi = webcam.getImage();
g.drawImage(bi,x,y,Width,Height,null);
}
整体代码
在窗体上输出视频
import com.github.sarxos.webcam.Webcam;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class VideoUI extends JFrame {
Graphics g;
BufferedImage bi;
public void initUI(){
this.setSize(1600,1000);
this.setTitle("video");
this.setDefaultCloseOperation(3);
this.setVisible(true);
this.setLayout(new FlowLayout());
g = this.getGraphics();
this.video();
}
public void video(){
Webcam webcam = Webcam.getDefault();
webcam.open();
while (true) {
bi = webcam.getImage();
g.drawImage(bi,100,100, bi.getWidth(), bi.getHeight(), null);
}
}
public static void main(String[] args){
VideoUI videoui = new VideoUI();
videoui.initUI();
}
}