美文网首页小程序
微信小程序+人脸识别

微信小程序+人脸识别

作者: 小李不小 | 来源:发表于2020-11-13 22:09 被阅读0次

为什么在原有的基础上增加人脸识别呢,因为我也厌倦了账号+密码的登录方式,所以想试一试在原有的功能上采用人脸识别登录。
识别过程借助于百度AI,服务器依旧是 SSM 框架。废话少说下面直接进入主题

微信小程序


  faceLogin:function(){

    var flagTemp = '';

    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['camera'],
  

      success: function (res) {
        wx.showLoading({
          title: '识别中',
        })
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: Api1,//使用人脸识别接口
          //method: 'GET',
          filePath: tempFilePaths[0],
          header: {
            'content-type': 'application/json' // 默认值
          },
          name: 'files',          
          success: function (res) {
            that.flagTemp = res.data;
            console.log("flag" + that.flagTemp);
          if (res.data != 0) {
            var uUsername = that.flagTemp;
            console.log(uUsername)

            user = {
              uUsername: uUsername,              
            }

            wx.request({          
              url: Api2,
              method: 'GET',
              data: user,
              header: {
                "Content-Type": "application/x-www-form-urlencoded"  // 默认值
              },
              success: function (res) {
                wx.hideLoading();
                app.globalData.userInfo = res.data;
                console.log(res.data);
                if (res.data != 0) {
                  wx.switchTab({
                    url: '../index/index'
                  })
                } else {
                  wx.showModal({
                    title: '识别失败',
                    content: '请重新识别',
                    showCancel: false, //不显示取消按钮
                    confirmText: '确定'
                  })
                }
              }
            })
          }
          
          }
        })
      }
    })

  },

只允许用户调用摄像头进行拍照,并调用文件上传API将图片上传进客户端获取用户名后在使用request方法对SpringMVC的Action进行用户查询,实现登录功能。

注意:如果不使用wx.request进行数据申请,是取不到服务端返回的JSON数据的
服务端代码

Base64Util

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.parking.util;

public class Base64Util {
    private static final char last2byte = (char)Integer.parseInt("00000011", 2);
    private static final char last4byte = (char)Integer.parseInt("00001111", 2);
    private static final char last6byte = (char)Integer.parseInt("00111111", 2);
    private static final char lead6byte = (char)Integer.parseInt("11111100", 2);
    private static final char lead4byte = (char)Integer.parseInt("11110000", 2);
    private static final char lead2byte = (char)Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    public Base64Util() {
    }

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int)((double)from.length * 1.34D) + 3);
        int num = 0;
        char currentByte = 0;

        int i;
        for(i = 0; i < from.length; ++i) {
            for(num %= 8; num < 8; num += 6) {
                switch(num) {
                case 0:
                    currentByte = (char)(from[i] & lead6byte);
                    currentByte = (char)(currentByte >>> 2);
                case 1:
                case 3:
                case 5:
                default:
                    break;
                case 2:
                    currentByte = (char)(from[i] & last6byte);
                    break;
                case 4:
                    currentByte = (char)(from[i] & last4byte);
                    currentByte = (char)(currentByte << 2);
                    if(i + 1 < from.length) {
                        currentByte = (char)(currentByte | (from[i + 1] & lead2byte) >>> 6);
                    }
                    break;
                case 6:
                    currentByte = (char)(from[i] & last2byte);
                    currentByte = (char)(currentByte << 4);
                    if(i + 1 < from.length) {
                        currentByte = (char)(currentByte | (from[i + 1] & lead4byte) >>> 4);
                    }
                }

                to.append(encodeTable[currentByte]);
            }
        }

        if(to.length() % 4 != 0) {
            for(i = 4 - to.length() % 4; i > 0; --i) {
                to.append("=");
            }
        }

        return to.toString();
    }
}
此工具类用于将图片文件转换为 Base64 字符串的形式

FileUtil

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.parking.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileUtil {
    public FileUtil() {
    }

    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if(!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int)file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];

                int len1;
                while(-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                byte[] var9 = var7;
                return var9;
            } finally {
                try {
                    if(in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
}

此工具类用于处理图片文件

- HttpUtil 
package com.parking.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;


public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);


        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();
 
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}

人脸识别登录

    @ResponseBody
    @RequestMapping(value = "/FaceLogin", method = RequestMethod.POST)
    public Object loginFace(@RequestParam("files") CommonsMultipartFile file,
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String resMsg = "";
        String path = null;
        

        try {

            long startTime = System.currentTimeMillis();

            System.out.println("fileName:" + file.getOriginalFilename());
            path = request.getSession().getServletContext()
                    .getRealPath("upload");
            System.out.println("path:" + path);

            String fileTyle = ".png";// 全部以png格式进行保存
            String newFileName = "tempLogin" + fileTyle;
            System.out.println(newFileName);
            System.out.println(fileTyle);
            File newFile = new File(path, newFileName);

            file.transferTo(newFile);
            long endTime = System.currentTimeMillis();
            System.out.println("运行时间:" + String.valueOf(endTime - startTime)
                    + "ms");
            resMsg = "1";


        } catch (FileNotFoundException e) {

            e.printStackTrace();
            resMsg = "0";
        }

        System.out.println(resMsg);
        
        
        if(resMsg.equals("1")){
            // 进行人脸识别
            String username = (String)faceVerify(path+"\\tempLogin.png");
            
            System.out.println("username"+username);
            
            
            return username;
        }
        
        
        return 0;       
        

    }


    public Object faceVerify(String pathFile) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
        try {

            byte[] bytes = FileUtil
                    .readFileByBytes(pathFile);
            String image = Base64Util.encode(bytes);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", image);
            map.put("image_type", "BASE64");
            map.put("liveness_control", "NORMAL");
            map.put("group_id_list", "park_sys");
            map.put("quality_control", "NONE");

            String param = GsonUtils.toJson(map);

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

            String result = HttpUtil.post(url, accessToken, "application/json",
                    param);
            System.out.println(result);

            // 处理返回JSON
            JSONObject json;
            json = JSONObject.fromObject(result);
            
            //获取识别状态
            String code = json.getString("error_code");
            String msg  = json.getString("error_msg");
            
                        
            
            //人脸识别成功
            if (code.equals("0")&&msg.equals("SUCCESS")){
                JSONArray JArray = json.getJSONObject("result").getJSONArray("user_list");
                json = JSONObject.fromObject(JArray.get(0).toString());
                System.out.println(json.getString("user_id"));
                return json.getString("user_id");
            }else{
                return "Error";
            }
            
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

实现思路是从微信客户端获取上传的文件图片,并调用百度人脸识别接口与人脸库图片进行匹配识别,获取返回的用户信息,调用Service方法进行判断是否成功登录。

相关文章

网友评论

    本文标题:微信小程序+人脸识别

    本文链接:https://www.haomeiwen.com/subject/oxkhyktx.html