Java 调用摄像头
更新时间:2020.6.27 12:45
- 引入 pom.xml 依赖
<dependency>
<groupId>com.github.sarxos</groupId>
<artifactId>webcam-capture</artifactId>
<version>0.3.12</version>
</dependency>
- 测试代码
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.WebcamUtils;
import com.github.sarxos.webcam.util.ImageUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestWebCam {
private static JFrame window;
public static void main(String[] args) throws InterruptedException {
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);
JFrame window = new JFrame("Test webcam panel");
window.add(panel);
window.setResizable(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
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://" + System.currentTimeMillis();
WebcamUtils.capture(webcam, fileName, ImageUtils.FORMAT_PNG);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
JOptionPane.showMessageDialog(null, "拍照成功");
button.setEnabled(true);
return;
}
});
}
});
}
}
- Base64Utils:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Base64Utils {
public static String encodeBase64File(String path) throws Exception{
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
public static void decoderBase64File(String base64Code,String targetPath) throws Exception{
byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
FileOutputStream out = new FileOutputStream(targetPath);
out.write(buffer);
out.close();
}
}
- CamUtils
import com.github.sarxos.webcam.*;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class CamUtils{
private static Webcam webcam = null;
private static WebcamPanel panel = null;
static {
webcam = Webcam.getDefault();
webcam.setViewSize(WebcamResolution.VGA.getSize());
panel = new WebcamPanel(webcam);
panel.setFPSDisplayed(true);
panel.setDisplayDebugInfo(true);
panel.setImageSizeDisplayed(true);
panel.setMirrored(true);
}
public static WebcamPanel getWebcamPanel(){
return panel;
}
public static void takePhoto(String photoName){
String url = null;
try {
url = new File("").getCanonicalPath() + "/img/" + photoName + ".png";
ImageIO.write(webcam.getImage(), "PNG", new File(url));
} catch (IOException e) {
e.printStackTrace();
}
}
}
- FaceUtils(百度人脸识别)
import com.baidu.aip.face.AipFace;
import main.Main;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.swing.*;
import java.util.HashMap;
public class FaceUtils {
private static AipFace aipFace = null;
public static final String APP_ID = "你的APP_ID";
public static final String API_KEY = "你的API_KEY";
public static final String SECRET_KEY = "你的SECRET_KEY";
static {
aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
}
public static boolean checkUser(String img){
int index = search(img);
if(index == Main.user.getId()){
return true;
}else {
return false;
}
}
public static boolean check(String img) {
HashMap<String, String> options = new HashMap<String, String>();
String string = "";
try {
string = Base64Utils.encodeBase64File(img);
} catch (Exception e) {
e.printStackTrace();
}
String image = string;
String imageType = "BASE64";
JSONObject res = aipFace.detect(image, imageType, options);
if(!res.getString("error_msg").equals("SUCCESS")){
JOptionPane.showMessageDialog(null,"暂时不能打卡!请联系管理员!","错误!",JOptionPane.ERROR_MESSAGE);
}else{
JSONObject result = res.getJSONObject("result");
JSONArray face_list = result.getJSONArray("face_list");
if (face_list.getJSONObject(0).getDouble("face_probability") > 0.8) {
return true;
} else {
JOptionPane.showMessageDialog(null, "人脸可能性低,请重新录入!", "错误!", JOptionPane.ERROR_MESSAGE);
}
}
return false;
}
public static int search(String img){
if(check(img)) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("quality_control", "NORMAL");
options.put("liveness_control", "LOW");
String string = "";
try {
string = Base64Utils.encodeBase64File(img);
} catch (Exception e) {
e.printStackTrace();
}
String image = string;
String imageType = "BASE64";
String groupIdList = "people_01";
JSONObject res = aipFace.search(image, imageType, groupIdList, options);
if (res.getString("error_msg").equals("match user is not found")) {
return 0;
} else {
if (!res.getString("error_msg").equals("SUCCESS")) {
JOptionPane.showMessageDialog(null, "未找到该用户,请将脸贴近摄像头!", "错误!", JOptionPane.ERROR_MESSAGE);
return -1;
} else {
if (res.getJSONObject("result").getJSONArray("user_list").getJSONObject(0).getDouble("score") > 85) {
return Integer.parseInt(res.getJSONObject("result").getJSONArray("user_list").getJSONObject(0).getString("user_id"));
}
}
}
}
return 0;
}
public static boolean rigister(String img){
if(check(img)) {
if (search(img) == 0) {
HashMap<String, String> options = new HashMap<String, String>();
String str = Integer.toString(Main.user.getId());
options.put("user_info", "注册时间:" + DateUtils.getDate());
options.put("quality_control", "NORMAL");
options.put("liveness_control", "LOW");
String string = "";
try {
string = Base64Utils.encodeBase64File(img);
} catch (Exception e) {
e.printStackTrace();
}
String image = string;
String imageType = "BASE64";
String groupId = "people_01";
String userId = Integer.toString(Main.user.getId());
JSONObject res = aipFace.addUser(image, imageType, groupId, userId, options);
return true;
}else{
JOptionPane.showMessageDialog(null,"您以注册人脸信息,请不要重复注册!","错误!",JOptionPane.ERROR_MESSAGE);
}
}
return false;
}
}
- DateUtils(时间获取和自动刷新)
import dao.impl.ClockDaoImpl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
class Dates implements Runnable{
private Date date = new Date();
public void run() {
while (true){
date = new Date();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public Date getDate() {
return date;
}
}
public class DateUtils{
private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
private static SimpleDateFormat sdf2 = new SimpleDateFormat("HH时mm分");
private static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
private static SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat sdf5 = new SimpleDateFormat("HH:mm");
private static Dates dates = new Dates();
static {
new Thread(dates).start();
}
public static String getDate(){
return sdf1.format(dates.getDate());
}
public static String getTime(){
return sdf5.format(dates.getDate());
}
public static String getTime(Date date){
return sdf2.format(date);
}
public static String formatFromMDatebaseUpdate(int id){
return sdf1.format(new ClockDaoImpl().findByID(id).getUpDate());
}
public static String formatFromMDatebaseDowndate(int id){
return sdf1.format(new ClockDaoImpl().findByID(id).getDownDate());
}
public static Date getDay(String s){
try {
return sdf3.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Date getDateFromDatebase(String s){
try {
return sdf4.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String getDay(Date date){
return sdf3.format(date);
}
}
- 调用摄像头依赖的 github 地址:https://github.com/sarxos/webcam-capture