Java 实现人脸识别(基于百度人脸识别API)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caox_nazi/article/details/80838143

百度人脸识别技术文档

1.人脸识别的工具类和实体类

<dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.4.0</version>
        </dependency>

package com.baofoo.admin.web.request.controller;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.FaceVerifyRequest;
import com.baidu.aip.face.MatchRequest;
import com.baidu.aip.util.Base64Util;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by BF100 on 2018/6/25.
 */
public class FaceIdentifyUtil {
    //设置APPID/AK/SK
    public static final String APP_ID = "11429094";
    public static final String API_KEY = "V0wjNP0yctaIHqrvfGbfaKkC";
    public static final String SECRET_KEY = "GQnl9x5bVrqP5hUSRldwZYuzQznT6iFs";

    static AipFace client = null;
    static {
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 可选:设置网络连接参数
        // 设置http代理
        // client.setHttpProxy("proxy_host", proxy_port);
        // 设置socket代理
        // client.setSocketProxy("proxy_host", proxy_port);
        // 可选:设置log4j日志输出格式,若不设置,则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "src/main/java/log4j.properties");
        client.setConnectionTimeoutInMillis(2000);
        // 可选:设置代理服务器地址, http和socket二选一,或者均不设置
        client.setSocketTimeoutInMillis(60000);
    }
    /**
     * 人脸检测
     * @param file
     * @param max_face_num
     * @return
     */
    public static String detectFace(File file, String max_face_num) {
        try {
            return detectFace(FileToByte(file), max_face_num);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸检测
     * @param arg0
     * @param max_face_num
     * @return
     */
    public static String detectFace(byte[] arg0, String max_face_num) {
        try {

            HashMap<String, String> options = new HashMap<String, String>();
            options.put("face_field", "age,beauty,expression,faceshape,gender,glasses,race,qualities");
            options.put("max_face_num", "2");
            options.put("face_type", "LIVE");

            // 图片数据
            String imgStr = Base64Util.encode(arg0);
            String imageType = "BASE64";
            JSONObject res = client.detect(imgStr, imageType, options);
            System.out.println(res.toString(2));
            return res.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸比对
     * @param file1
     * @param file2
     * @return
     */
    public static String matchFace(File file1, File file2) {
        try {
            return matchFace(FileToByte(file1), FileToByte(file2));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸比对
     * @param arg0
     * @param arg1
     * @return
     */
    public static String matchFace(byte[] arg0, byte[] arg1) {
        String imgStr1 = Base64Util.encode(arg0);
        String imgStr2 = Base64Util.encode(arg1);
        MatchRequest req1 = new MatchRequest(imgStr1, "BASE64");
        MatchRequest req2 = new MatchRequest(imgStr2, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        JSONObject res = client.match(requests);
        return res.toString();
    }

    /**
     * 人脸搜索
     * @param file
     * @param groupIdList
     * @param userId
     * @return
     */
    public static String searchFace(File file, String groupIdList, String userId) {
        try {
            return searchFace(FileToByte(file), groupIdList, userId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸搜索
     * @param arg0
     * @param groupIdList
     * @param userId
     * @return
     */
    public static String searchFace(byte[] arg0, String groupIdList, String userId) {
        String imgStr = Base64Util.encode(arg0);
        String imageType = "BASE64";
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        if (userId != null) {
            options.put("user_id", userId);
        }
        options.put("max_user_num", "1");
        JSONObject res = client.search(imgStr, imageType, groupIdList, options);
        return res.toString(2);
    }

    /**
     * 注册用户
     * @param file
     * @param userInfo
     * @param userId
     * @param groupId
     * @return
     */
    public static String addUser(File file, String userInfo, String userId, String groupId) {
        try {
            return addUser(FileToByte(file), userInfo, userId, groupId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 注册用户
     * @param arg0
     * @param userInfo
     * @param userId
     * @param groupId
     * @return
     */
    public static String addUser(byte[] arg0, String userInfo, String userId, String groupId) {
        String imgStr = Base64Util.encode(arg0);
        String imageType = "BASE64";
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", userInfo);
        options.put("quality_control", "NORMAL");
//        options.put("liveness_control", "LOW");

        JSONObject res = client.addUser(imgStr, imageType, groupId, userId, options);
        return res.toString(2);
    }

    /**
     * 查询用户信息
     * @param userId
     * @param groupId
     * @return
     */
    public static String searchUserInfo(String userId, String groupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 用户信息查询
        JSONObject res = client.getUser(userId, groupId, options);
        return res.toString(2);
    }

    /**
     * 获取用户人脸列表
     * @param userId
     * @param groupId
     * @return
     */
    public static String getUserFaceList(String userId, String groupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 获取用户人脸列表
        JSONObject res = client.faceGetlist(userId, groupId, options);
        return res.toString(2);
    }

    /**
     * 获取一组用户
     * @param groupId
     * @param returnNum
     * @return
     */
    public static String getGroupUsers(String groupId, String returnNum) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("start", "0");
        if (returnNum != null) {
            options.put("length", returnNum);
        }
        // 获取用户列表
        JSONObject res = client.getGroupUsers(groupId, options);
        return res.toString(2);
    }

    /**
     * 更新用户
     * @param file
     * @param userInfo
     * @param userId
     * @param groupId
     * @return
     */
    public static String updateUser(File file, String userInfo, String userId, String groupId) {
        try {
            return updateUser(FileToByte(file), userInfo, userId, groupId);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新用户
      * @param arg0
     * @param userInfo
     * @param userId
     * @param groupId
     * @return
     */
    public static String updateUser(byte[] arg0, String userInfo, String userId, String groupId) {
        String imgStr = Base64Util.encode(arg0);
        String imageType = "BASE64";
        HashMap<String, String> options = new HashMap<String, String>();
        if (userInfo != null) {
            options.put("user_info", userInfo);
        }
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");

        JSONObject res = client.updateUser(imgStr, imageType, groupId, userId, options);
        return res.toString(2);
    }

    /**
     * 删除用户 人脸删除
     * @param userId
     * @param groupId
     * @param faceToken
     * @return
     */
    public static String deleteUserFace(String userId, String groupId, String faceToken) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 人脸删除
        JSONObject res = client.faceDelete(userId, groupId, faceToken, options);
        return res.toString();
    }

    /**
     * 组用户复制
     * @param userId
     * @param srcGroupId
     * @param dstGroupId
     * @return
     */
    public static String userCopy(String userId, String srcGroupId, String dstGroupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("src_group_id", srcGroupId);
        options.put("dst_group_id", dstGroupId);
        // 复制用户
        JSONObject res = client.userCopy(userId, options);
        return res.toString(2);
    }

    /**
     * 删除用户
     * @param userId
     * @param groupId
     * @return
     */
    public static String deleteUser(String userId, String groupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 人脸删除
        JSONObject res = client.deleteUser(groupId, userId, options);
        return res.toString();
    }

    /**
     * 增加组信息
     * @param groupId
     * @return
     */
    public static String addGroup(String groupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 创建用户组
        JSONObject res = client.groupAdd(groupId, options);
        return res.toString();
    }

    /**
     * 删除用户组
     * @param groupId
     * @return
     */
    public static String deleteGroup(String groupId) {
        HashMap<String, String> options = new HashMap<String, String>();
        // 创建用户组
        JSONObject res = client.groupDelete(groupId, options);
        return res.toString();
    }

    /**
     * 获取组列表
     * @param length
     * @return
     */
    public static String getGroupList(String length) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("start", "0");
        options.put("length", length);
        // 组列表查询
        JSONObject res = client.getGroupList(options);
        return res.toString();
    }

    /**
     * 活体检测
     * @param arg0
     * @return
     */
    public static String faceverify(byte[] arg0){
        String imgStr = Base64Util.encode(arg0);
        String imageType = "BASE64";
        FaceVerifyRequest req = new FaceVerifyRequest(imgStr, imageType);
        ArrayList<FaceVerifyRequest> list = new ArrayList<FaceVerifyRequest>();
        list.add(req);
        JSONObject res = client.faceverify(list);
        return res.toString();
    }

    /**
     * 身份验证
     * @param arg0
     * @param idCardNumber
     * @param name
     * @return
     */
    public static String personVerify(byte[] arg0, String idCardNumber, String name){
        String imgStr = Base64Util.encode(arg0);
        String imageType = "BASE64";
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");

        // 身份验证
        JSONObject res = client.personVerify(imgStr, imageType, idCardNumber, name, options);
        return  res.toString(2);
    }


    /**
     * 将文件转为流
     * @param file
     * @return
     * @throws IOException
     */
    public static byte[] FileToByte(File file) throws IOException {
        // 将数据转为流
        InputStream content = new FileInputStream(file);
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = content.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        // 获得二进制数组
        return swapStream.toByteArray();
    }
}

将文件转换为流:

package com.cn.hnust.util;

import java.io.*;

/**
 * Created by BF100 on 2018/6/22.
 */
public class FileUtil {
    /**
     * 根据文件路径读取byte[] 数组
     */
    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();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }   

V3人脸检测javabean

package com.baofoo.admin.web.request.controller;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.List;

/**
 * Created by BF100 on 2018/6/26.
 * V3版本人脸检测javabean
 */
@Setter
@Getter
@ToString
public class FaceV3DetectBean {
    private int error_code;
    private String error_msg;
    private long log_id;
    private long timestamp;
    private int cached;
    private Result result;

    /**
     * Result
     */
    public static class Result {
        private int face_num;
        private List<Face_list> face_list;
        public void setFace_num(int face_num) {
            this.face_num = face_num;
        }
        public int getFace_num() {
            return face_num;
        }

        public void setFace_list(List<Face_list> face_list) {
            this.face_list = face_list;
        }
        public List<Face_list> getFace_list() {
            return face_list;
        }
    }

    /**
     * Face_list
     */
    public static class Face_list {
        private String face_token;
        private Location location;
        private int face_probability;
        private Angle angle;
        private int age;
        private double beauty;
        private Expression expression;
        private Face_shape face_shape;
        private Gender gender;
        private Glasses glasses;
        private List<Landmark> landmark;
        private List<Landmark72> landmark72;
        private Race race;

        public void setFace_token(String face_token) {
            this.face_token = face_token;
        }
        public String getFace_token() {
            return face_token;
        }

        public void setLocation(Location location) {
            this.location = location;
        }
        public Location getLocation() {
            return location;
        }

        public void setFace_probability(int face_probability) {
            this.face_probability = face_probability;
        }
        public int getFace_probability() {
            return face_probability;
        }

        public void setAngle(Angle angle) {
            this.angle = angle;
        }
        public Angle getAngle() {
            return angle;
        }

        public void setAge(int age) {
            this.age = age;
        }
        public int getAge() {
            return age;
        }

        public void setBeauty(double beauty) {
            this.beauty = beauty;
        }
        public double getBeauty() {
            return beauty;
        }

        public void setExpression(Expression expression) {
            this.expression = expression;
        }
        public Expression getExpression() {
            return expression;
        }

        public void setFace_shape(Face_shape face_shape) {
            this.face_shape = face_shape;
        }
        public Face_shape getFace_shape() {
            return face_shape;
        }

        public void setGender(Gender gender) {
            this.gender = gender;
        }
        public Gender getGender() {
            return gender;
        }

        public void setGlasses(Glasses glasses) {
            this.glasses = glasses;
        }
        public Glasses getGlasses() {
            return glasses;
        }

        public void setLandmark(List<Landmark> landmark) {
            this.landmark = landmark;
        }
        public List<Landmark> getLandmark() {
            return landmark;
        }

        public void setLandmark72(List<Landmark72> landmark72) {
            this.landmark72 = landmark72;
        }
        public List<Landmark72> getLandmark72() {
            return landmark72;
        }

        public void setRace(Race race) {
            this.race = race;
        }
        public Race getRace() {
            return race;
        }
    }

    /**
     * Rece
     */
    public static class Race{
        private String type;
        private double probability;

        public void setType(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }

        public void setProbability(double probability) {
            this.probability = probability;
        }
        public double getProbability() {
            return probability;
        }
    }

    /**
     * Landmark72
     */
    public static class Landmark72{
        private double x;
        private double y;
        public void setX(double x) {
            this.x = x;
        }
        public double getX() {
            return x;
        }

        public void setY(double y) {
            this.y = y;
        }
        public double getY() {
            return y;
        }
    }

    /**
     * Landmark
     */
    public static class Landmark {
        private double x;
        private double y;
        public void setX(double x) {
            this.x = x;
        }
        public double getX() {
            return x;
        }

        public void setY(double y) {
            this.y = y;
        }
        public double getY() {
            return y;
        }
    }

    /**
     * Glasses
     */
    public static class Glasses {
        private String type;
        private double probability;
        public void setType(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }
        public void setProbability(double probability) {
            this.probability = probability;
        }
        public double getProbability() {
            return probability;
        }
    }

    /**
     * Gender
     */
    public static class Gender {
        private String type;
        private double probability;
        public void setType(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }
        public void setProbability(double probability) {
            this.probability = probability;
        }
        public double getProbability() {
            return probability;
        }
    }


    /**
     * Face_shape
     */
    public static class Face_shape {
        private String type;
        private double probability;
        public void setType(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }

        public void setProbability(double probability) {
            this.probability = probability;
        }
        public double getProbability() {
            return probability;
        }
    }

    /**
     * Expression
     */
    public static class Expression {
        private String type;
        private double probability;
        public void setType(String type) {
            this.type = type;
        }
        public String getType() {
            return type;
        }
        public void setProbability(double probability) {
            this.probability = probability;
        }
        public double getProbability() {
            return probability;
        }
    }

    /**
     * Angle
     */
    public static class Angle {
        private double yaw;
        private double pitch;
        private double roll;
        public void setYaw(double yaw) {
            this.yaw = yaw;
        }
        public double getYaw() {
            return yaw;
        }

        public void setPitch(double pitch) {
            this.pitch = pitch;
        }
        public double getPitch() {
            return pitch;
        }

        public void setRoll(double roll) {
            this.roll = roll;
        }
        public double getRoll() {
            return roll;
        }
    }

    /**
     * Location
     */
    public static class Location {
        private double left;
        private double top;
        private int width;
        private int height;
        private int rotation;
        public void setLeft(double left) {
            this.left = left;
        }
        public double getLeft() {
            return left;
        }

        public void setTop(double top) {
            this.top = top;
        }
        public double getTop() {
            return top;
        }

        public void setWidth(int width) {
            this.width = width;
        }
        public int getWidth() {
            return width;
        }

        public void setHeight(int height) {
            this.height = height;
        }
        public int getHeight() {
            return height;
        }

        public void setRotation(int rotation) {
            this.rotation = rotation;
        }
        public int getRotation() {
            return rotation;
        }

    }
}

2.人脸识别java后台核心代码

@ResponseBody
    @RequestMapping("ajaxRequestInfo.do")
    public Map<String,Object> ajaxRequestInfo(HttpServletRequest request, RequestQueryForm form,
                                                   @RequestParam(value="file", required=false) MultipartFile file) {
        Map<String,Object> map = new HashMap<String,Object>();

        try {
            if(null != file) {
                //将数据转为流
                InputStream content = file.getInputStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = content.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                //获得二进制数组
                byte[] in2b = swapStream.toByteArray();
                //调用人脸检测的方法
                String  str = FaceIdentifyUtil.detectFace(in2b,""+1);
                JSONObject job = new JSONObject(FaceIdentifyUtil.faceverify(in2b));
                System.out.println(job.toString());
                JSONObject testData = job.getJSONObject("result");

                JSON json = JSON.parseObject(str);
                FaceV3DetectBean bean = JSON.toJavaObject(json, FaceV3DetectBean.class);
                JSONArray arr = new JSONArray();
                // 美丑打分
                map.put("beauty",bean.getResult().getFace_list().get(0).getBeauty());
                // 年龄
                map.put("age",bean.getResult().getFace_list().get(0).getAge());
                // 性别
                map.put("gender",bean.getResult().getFace_list().get(0).getGender().getType());
                // 获取是否带眼睛 0-无眼镜,1-普通眼镜,2-墨镜
                map.put("glasses",bean.getResult().getFace_list().get(0).getGlasses().getType());
                // 获取是否微笑,0,不笑;1,微笑;2,大笑
                map.put("expression", bean.getResult().getFace_list().get(0).getExpression().getType());

                for(int i=0;i<bean.getResult().getFace_list().size();i++){
                    JSONObject jsonObject = new JSONObject();
                    //获取年龄
                    int ageOne = bean.getResult().getFace_list().get(i).getAge();
                    //处理年龄
                    String age =String.valueOf(new BigDecimal(ageOne).setScale(0, BigDecimal.ROUND_HALF_UP));
                    jsonObject.put("age", age);

                    //获取美丑打分
                    Double beautyOne = (Double) bean.getResult().getFace_list().get(i).getBeauty();
                    //处理美丑打分
                    String beauty =String.valueOf(new BigDecimal(beautyOne).setScale(0, BigDecimal.ROUND_HALF_UP));
                    jsonObject.put("beauty", beauty);

                    //获取性别  male(男)、female(女)
                    String gender = (String) bean.getResult().getFace_list().get(i).getGender().getType();
                    jsonObject.put("gender", gender);

                    //获取是否带眼睛 0-无眼镜,1-普通眼镜,2-墨镜
                    String glasses =  bean.getResult().getFace_list().get(i).getGlasses().getType();
                    jsonObject.put("glasses", String.valueOf(glasses));

                    //获取是否微笑,0,不笑;1,微笑;2,大笑
                    String expression =  bean.getResult().getFace_list().get(i).getExpression().getType();
                    jsonObject.put("expression", String.valueOf(expression));
                    arr.add(jsonObject);
                }
                map.put("strjson", arr.toString());
                map.put("face_liveness", testData.get("face_liveness"));
                map.put("success", true);
                log.info("call ajaxRequestInfo result:{}, arr:{}, arr.toString:{}, bean.getResult().getFace_list().size():{}",map.toString(), arr, arr.toString(), bean.getResult().getFace_list().size());
            }
        } catch (Exception e) {
            log.error("call ajaxRequestInfo 检测异常 ******", e);
            e.printStackTrace();
            map.put("success", false);
            map.put("data", e.getMessage());
        }
        return map;
    }

3.前端html页面和javascript代码

<form  id="add_form" name="add_form" action="" method="post" enctype="multipart/form-data" onsubmit="return checkformDelSpace(this)">
<!-- 图片路径隐藏域 -->
<!-- 主体部分 -->
<div class="content">
	<div class="row-fluid">
		<div class="span12">
			<div class="widget">
				<!-- 选项卡头 -->
				<div class="head dark">
					<div class="icon">
						<i class="icos-stats-up"></i>
					</div>
					<h2>人脸识别</h2>
				</div>
				<div class="block-fluid">
					<div class="tab-content">
						<div class="tab-pane active">
							<!-- 头 -->
							<div class="head">
								<div class="icon">
									<i class="icosg-clipboard1"></i>
								</div>
								<h2>人脸识别<span >(其中 <span style="color: red;font-size: larger;font-weight: inherit" >*</span> 为必填项)</span></h2>
							</div>


							<%--<div class="row-form">--%>
								<%--<div class="span2">附件</div>--%>
								<%--<div class="span10">--%>
									<%--<div class="ajaxuploadfile_component_1">--%>
										<%--<div class="ajaxuploadfile_one">--%>
											<%--<div class="span12">--%>
												<%--<div class="input-append file">--%>
													<%--<input type="file" name="file"/>--%>
													<%--<input type="text" id="addFile" readonly="readonly"--%>
														   <%--class="funcCall[checkFile]"/>--%>
													<%--<button class="btn" type="button">浏览</button>--%>
												<%--</div>--%>
											<%--</div>--%>
										<%--</div>--%>
									<%--</div>--%>
								<%--</div>--%>
							<%--</div>--%>

							<div class="row-form">
								 <input type='file' id='iptfileupload' name="file" onchange='show()' value='' />
							</div>

							<div class="row-form">
								 <img src='#' alt='' id='img' style="width: 260px;height: 230px;" />
								  <canvas style="" hidden="hidden"  id="canvas" style="width: 260px;height: 230px;"></canvas>
							</div>

							<div class="row-form">
								<h1>人脸检测实时数据</h1>
								<span>年龄:</span><span id="age"></span><br/>
								<span>颜值:</span><span id="beauty" ></span><br/>
								<span>性别:</span><span id="gendergender"></span><br/>
								<span>是否戴眼镜:</span><span id="glasses"></span><br/>
								<span>表情:</span><span id="expression"></span><br/>
								<span>活体分数:</span><span id="faceverify"></span><br/>
							</div>

						</div><!--tab-plane active-->
						<div class="toolbar bottom TAC">
								<input style="width: 10%" id="doSave" class="btn btn-primary" type="button" value="提交"/>      <input style="width: 10%" id="doChannel" class="btn" type="button" value="取消 " onclick="javascript :history.go(-1)" />
						</div>
					</div><!--tab-content-->
				</div>
			</div>
		</div>
	</div>
</div>
<!-- 主体部分 -->
</form>
<script type="text/javascript">

	//判断浏览器是否支持HTML5 Canvas
//	window.onload = function () {
//		try {
//			//动态创建一个canvas元 ,并获取他2Dcontext。如果出现异常则表示不支持 document.createElement("canvas").getContext("2d");
//			document.getElementById("support").innerHTML = "浏览器支持HTML5 CANVAS";
//		}
//		catch (e) {
//			document.getElementById("support").innerHTML = "浏览器不支持HTML5 CANVAS";
//		}
//	};

	/**
	 * 其中show() 和 getPath() 方法 是实现读取图片后并且立即显示出来
     */
	function show(){
		//以下即为完整客户端路径
		var file_img=document.getElementById("img"),
				iptfileupload = document.getElementById('iptfileupload');
		getPath(file_img,iptfileupload,file_img) ;
	}
	function getPath(obj,fileQuery,transImg) {
		var imgSrc = '', imgArr = [], strSrc = '' ;
		if(window.navigator.userAgent.indexOf("MSIE")>=1){ // IE浏览器判断
			if(obj.select){
				obj.select();
				var path=document.selection.createRange().text;
				alert(path) ;
				obj.removeAttribute("src");
				imgSrc = fileQuery.value ;
				imgArr = imgSrc.split('.') ;
				strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
				if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
					obj.setAttribute("src",transImg);
					obj.style.filter=
							"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path+"', sizingMethod='scale');"; // IE通过滤镜的方式实现图片显示
				}else{
					//try{
					throw new Error('File type Error! please image file upload..');
					//}catch(e){
					// alert('name: ' + e.name + 'message: ' + e.message) ;
					//}
				}
			}else{
				// alert(fileQuery.value) ;
				imgSrc = fileQuery.value ;
				imgArr = imgSrc.split('.') ;
				strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
				if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
					obj.src = fileQuery.value ;
				}else{
					//try{
					throw new Error('File type Error! please image file upload..') ;
					//}catch(e){
					// alert('name: ' + e.name + 'message: ' + e.message) ;
					//}
				}
			}
		} else{
			var file =fileQuery.files[0];
			var reader = new FileReader();
			reader.onload = function(e){

				imgSrc = fileQuery.value ;
				imgArr = imgSrc.split('.') ;
				strSrc = imgArr[imgArr.length - 1].toLowerCase() ;
				if(strSrc.localeCompare('jpg') === 0 || strSrc.localeCompare('jpeg') === 0 || strSrc.localeCompare('gif') === 0 || strSrc.localeCompare('png') === 0){
					obj.setAttribute("src", e.target.result) ;
				}else{
					//try{
					throw new Error('File type Error! please image file upload..') ;
					//}catch(e){
					// alert('name: ' + e.name + 'message: ' + e.message) ;
					//}
				}
				// alert(e.target.result);
			}
			reader.readAsDataURL(file);
		}
	}
	//***********************************绑定单击事件**********************************
	$(function(){
		$("#iptfileupload").change(function () {
            var formData = new FormData(document.getElementById("add_form"));
            loadJs();
            $.ajax({
                url: "${ctx}/request/ajaxRequestInfo.do",
                method: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function (responseData) {
                    console.log(responseData);
                    var mes = eval(responseData);
                    console.log(mes);
                    if (mes.success) {
                        //alert(mes.strjson);
                        var jsonObj =  $.parseJSON(mes.strjson);
                        console.log(jsonObj);
                        //alert(jsonObj);
//                        var age = jsonObj[0].age;
//
//                        var beauty = jsonObj[0].beauty;
//                        var gendergender = jsonObj[0].gender;
//                        var glasses = jsonObj[0].glasses;
//                        var expression = jsonObj[0].expression

						var age = mes.age;
						var beauty = mes.beauty;
						var gendergender = mes.gender;
						var glasses = mes.glasses;
						var expression = mes.expression;


                        $("#age").html(age);
                        $("#beauty").html(beauty);
                        $("#faceverify").html(mes.face_liveness);

                        if(gendergender == 'male'){
                            $("#gendergender").html("男");
                        }else{
                            $("#gendergender").html("女");
                        }

                        if(glasses == 'none'){
                            $("#glasses").html("未戴眼镜");
                        }else if(glasses == 'common'){
                            $("#glasses").html("戴了普通眼镜");
                        }else{
                            $("#glasses").html("戴了墨镜");
                        }

                        if(expression == 'none'){
                            $("#expression").html("不笑");
                        }else if(expression == 'smile'){
                            $("#expression").html("微笑");
                        }else{
                            $("#expression").html("大笑");
                        }
                        closeBlockUI();
                    }else{
						closeBlockUI();
						showPagePrompts("error","检测失败!");
					}
                },error:function (e) {
                    closeBlockUI();
                    showPagePrompts("error","操作失败:"+e);
                }
            });
        });

		//保存
		$("#doSave").click(function(){
			var url="${ctx}/request/addRequestInfoAction.do";
			$("#add_form").ajaxSubmit({
				type:'post',
				url:url,
				success:function (responseData) {
					var mes = eval(responseData);
					if (mes.success) {
						//alert(mes.strjson);
						var jsonObj =  $.parseJSON(mes.strjson);
						console.log(jsonObj);
						//alert(jsonObj);
						var age = jsonObj[0].age;

						var beauty = jsonObj[0].beauty;
						var gendergender = jsonObj[0].gender;
						var glasses = jsonObj[0].glasses;
						var expression = jsonObj[0].expression

						$("#age").html(age);
						$("#beauty").html(beauty);
						$("#faceverify").html(mes.face_liveness);

						if(gendergender == 'male'){
							$("#gendergender").html("男");
						}else{
							$("#gendergender").html("女");
						}

						if(glasses == 'none'){
							$("#glasses").html("未戴眼镜");
						}else if(glasses == 'common'){
							$("#glasses").html("戴了普通眼镜");
						}else{
							$("#glasses").html("戴了墨镜");
						}

						if(expression == 'none'){
							$("#expression").html("不笑");
						}else if(expression == 'smile'){
							$("#expression").html("微笑");
						}else{
							$("#expression").html("大笑");
						}
					}
				},error:function (e) {
					showPagePrompts("error","操作失败:"+e);
				}
			});
		});
	});
</script>



展开阅读全文

没有更多推荐了,返回首页