import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.VideoWriter;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraCapture {
// 加载 OpenCV native 库
static {
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
} catch (UnsatisfiedLinkError e) {
System.err.println("加载 OpenCV 库失败:" + e.getMessage());
System.exit(1);
}
}
private JFrame frame;
private JLabel imageLabel;
private JButton btnCapture;
private JButton btnRecord;
private VideoCapture capture;
private VideoWriter writer;
private boolean recording = false;
private Size frameSize;
private final int fourcc = VideoWriter.fourcc('M', 'J', 'P', 'G'); // 使用 MJPG 编码
private final int fps = 20; // 帧率
public CameraCapture() {
initGUI();
startCamera();
}
// 初始化图形界面
private void initGUI() {
frame = new JFrame("摄像头拍照录像");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 用 JLabel 显示视频画面
imageLabel = new JLabel();
frame.add(imageLabel, BorderLayout.CENTER);
// 底部面板放置拍照与录像按钮
JPanel panel = new JPanel();
btnCapture = new JButton("拍照");
btnRecord = new JButton("开始录像");
panel.add(btnCapture);
panel.add(btnRecord);
frame.add(panel, BorderLayout.SOUTH);
// 拍照按钮事件
btnCapture.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
capturePhoto();
}
});
// 录像按钮事件:点击开始或停止录像
btnRecord.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
toggleRecording();
}
});
frame.setSize(800, 600);
frame.setVisible(true);
}
// 启动摄像头并在后台线程中捕获视频帧
private void startCamera() {
capture = new VideoCapture(0);
if (!capture.isOpened()) {
System.err.println("无法打开摄像头,请检查摄像头是否正常连接或被其他程序占用!");
System.exit(1);
}
// 获取第一帧来确定视频尺寸
Mat tempMat = new Mat();
capture.read(tempMat);