BaiduUtils.java 11.3 KB
package com.example.dahua.utils;

import com.alibaba.fastjson.JSON;
import com.example.dahua.async.ImageUtils;
import com.example.dahua.lib.CompressPic;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class BaiduUtils {

    private static BaiduUtils baiduUtils;

    public static BaiduUtils getBaiduUtils(){

        if (null==baiduUtils){
            synchronized (BaiduUtils.class){
                if (null==baiduUtils)baiduUtils=new BaiduUtils();
            }
        }
        return baiduUtils;
    }


    public boolean checkImg(String httpurl){
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
        try {

            List list = new ArrayList();
            Map<String, String> map = new HashMap<>();
            String image_type = "";
            String imgFilePath = httpurl;
            File target = new File("./huoti/");
            if (!target.exists()) target.mkdirs();
            File target1 = new File(target.getAbsolutePath(), new File(httpurl).getName());
            if (httpurl.startsWith("http")) image_type = "URL";
            else {
                CompressPic.CompressPic(httpurl, target1.getAbsolutePath(), "");//压缩后的图片
                image_type = "BASE64";
                httpurl = Base64Util.encode(image2byte(target1.getAbsolutePath()));
            }
            map.put("image", httpurl);
            map.put("image_type", image_type);
//            map.put("face_field","");
//            map.put("option","GATE");
            list.add(map);
            String param = GsonUtils.toJson(list);
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = getAuth();

            String result1 = HttpUtil.post(url, accessToken, "application/json", param);
            JSONObject jsonObject = new JSONObject(result1);
            String error_msg = jsonObject.optString("error_msg");
            JSONObject result = jsonObject.optJSONObject("result");
            if (error_msg.equals("SUCCESS")) {
                double face_liveness = result.optDouble("face_liveness", 0.00);//活体分数值
                JSONArray face_list = result.optJSONArray("face_list");
                JSONObject location = face_list.optJSONObject(0).optJSONObject("location");
                double rotation = location.optDouble("rotation", 0.0);//竖直方向旋转角度
                System.out.println(" face_liveness:" + face_liveness);
                if (face_liveness > 0.4) {
                    int angel = 0;
                    if (45 < rotation && rotation < 135) {//右向横图,需要旋转270度
                        System.out.println("旋转270度");
                        angel = 270;
                    } else if (rotation > -135 && rotation < -45) {//左向横图,需要旋转90度
                        System.out.println("旋转90度");
                        angel = 90;
                    } else if (rotation >= -180 && rotation <= -135 || rotation >= 135 && rotation <= 180) {//倒向图片,需要旋转180度
                        System.out.println("旋转180度");
                        angel = 180;
                    }
                    System.out.println("图片检验成功");
                    FileUtils.getInstance().writeLogs("检测成功:" + imgFilePath, FileUtils.checkSuc);
                    //E:\wwwhtdocs\SmartCampus\face17e50\School
                    //http://campus.myjxt.com//face17e5/School861/Student/GBZX20171134.jpg
                    //F:\wwwroot\smartcampus\face17e5
//                    imgFilePath =httpurl.replace("http://campus.myjxt.com","E:\\wwwhtdocs\\SmartCampus");
//                    imgFilePath = httpurl.replace("http://60.190.202.57:1000","F:\\wwwroot\\smartcampus");
//                    System.out.println("图片是否存在:" + imgFilePath);
                    if (angel != 0)
                        ImageUtils.rotatePhonePhoto(imgFilePath, angel);
                    return true;
                } else {
                    FileUtils.getInstance().writeLogs("检测失败,活体分数:" + face_liveness + " " + imgFilePath, FileUtils.checkFail);
                    System.out.println("图片不合格" + imgFilePath);
                    deleteImgFile(imgFilePath);
                    return false;
                }
            } else {
                System.out.println("检测失败");
                FileUtils.getInstance().writeLogs("检测失败:" + error_msg + imgFilePath, FileUtils.checkFail);
                deleteImgFile(imgFilePath);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 注册人脸到百度
     * @param file
     */
    private void addToBaidu(File file) {

        //学籍号或者教职工编号
        String userCode = file.getName().split("\\.")[0];



//        BaiduUtils.getBaiduUtils().addFace(file,)

    }

    //图片到byte数组
    public byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }

    private boolean deleteImgFile(String imgFilePath) {
        imgFilePath = imgFilePath.replace("http://campus.myjxt.com", "E:\\wwwhtdocs\\SmartCampus");
        File file = new File(imgFilePath);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 获取权限token
     *
     * @return 返回示例:
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "u6rV4YxRZmwzKj56N0DCW8eO";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "Krp3KhmIBdnNEsRa1LavMHuZl0KhQGVm";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     *
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.err.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
//            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }


    //注册人脸
    public String addFace(File img, String group_id, String user_id, String userInfo) {

        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";


        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", Base64Util.encode(InputStream2ByteArray(img.getAbsolutePath())));
            map.put("group_id", group_id);
            map.put("user_id", user_id);
            map.put("user_info", userInfo);
//            map.put("liveness_control", "NORMAL");
            map.put("image_type", "BASE64");
            map.put("quality_control", "NORMAL");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。

            String result = HttpUtil.post(url, getAuth(), "application/json", param);
            System.out.println(result);
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
            String error_msg = jsonObject.getString("error_msg");
            if (error_msg.equals("SUCCESS")) {

//                com.alibaba.fastjson.JSONObject faceResult = jsonObject.getJSONObject("result");

//                FacerecordBean facerecordBean = new FacerecordBean();
//
//                facerecordBean.setFace_token(faceResult.getString("face_token"));
//                facerecordBean.setGroup_id(group_id);
//                facerecordBean.setIntime(simpleDateFormat.format(new Date()));
//                facerecordBean.setUser_id(user_id);
//
//                facerecordService.addFacerecord(facerecordBean);
                return "注册成功";
            } else {
                return error_msg;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private byte[] InputStream2ByteArray(String filePath) throws IOException {

        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}