Java 调用摄像头以及一些 Utils

Java 调用摄像头

更新时间:2020.6.27 12:45
  1. 引入 pom.xml 依赖
	<dependency>
            <groupId>com.github.sarxos</groupId>
            <artifactId>webcam-capture</artifactId>
            <version>0.3.12</version>
        </dependency>
  1. 测试代码
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);  //设置按钮不可点击


                //实现拍照保存-------start
                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;
                    }
                });
                //实现拍照保存-------end

            }
        });
    }
}
  1. Base64Utils:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Base64Utils {
    /**
     * 将文件加密成base64字符串
     * @param path
     * @return
     * @throws Exception
     */
    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);
    }

    /**
     * 将base64解密后存入文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    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();
    }
}
  1. 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();
        }
    }
}
  1. 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);
    }

    /**
     * 检测人脸是否是当前用户
     * @param img
     * @return
     */
    public static boolean checkUser(String img){
        int index = search(img);
        if(index == Main.user.getId()){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 检测是否是人脸
     * @param img
     * @return
     */
    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);
        //System.out.println(res.toString(2));
        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;
    }

    /**
     * 在人脸库中搜索人脸
     * @param img
     * @return
     * 0表示前面没有弹框且该用户不是本人或没有该注册用户
     * -1表示有错误弹框
     * 非0和-1表示用户最匹配的用户ID
     */
    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);
            //System.out.println(res.toString(2));

            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;
        //用户不是本人
    }

    /**
     * 注册人脸,如果人脸已经存在,不能注册
     * @param img
     * @return
     */
    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);
                //System.out.println(res.toString(2));
                return true;
            }else{
                JOptionPane.showMessageDialog(null,"您以注册人脸信息,请不要重复注册!","错误!",JOptionPane.ERROR_MESSAGE);
            }
        }
        return false;
    }
}
  1. 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(){
//        List<Map<String,Object>> list = null;
//        try {
//            list = new ClockDaoImpl().findAll();
//        }catch (Exception e){
//            //结果为空异常
//        }
//        String s = "";
//        for(Map<String,Object> map : list){
//            s = (String)map.get("upDate");
//        }
//        Date[] dates = null;
//        if(list.size() == 0 || list == null){
//            return null;
//        }else {
//            dates = new Date[list.size()];
//            Date date = null;
//            for(int i = 0 ; i < dates.length ; i++) {
//                try {
//                    date = sdf4.parse(s);
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }
//                dates[i] = date;
//            }
//            return dates;
//        }
//    }

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

  1. 调用摄像头依赖的 github 地址:https://github.com/sarxos/webcam-capture
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值