微信公众号开发之调起拍照或从手机相册中选图接口

拍照或从手机相册中选图接口

wx.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
        var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
    }
});

直接上代码 bind_face.jsp(本文中的config接口注入权限验证配置在微信公众号开发之调起微信扫一扫接口已讲解过了,在这里就不赘述了。)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Expires" content="0"/>
    <script src="../../resources/js/jquery.min.js"></script>
    <link href="../../resources/css/layui.css" rel="stylesheet">
    <script src="../../resources/layui.js"></script>
    <link href="../../resources/css/wechat.css" rel="stylesheet">
    <script src="../../resources/js/jweixin-1.2.0.js"></script>
    <title>刷脸</title>
    <script>
        function bindFace() {
            choosePic();
        }

        function choosePic() {
            wx.chooseImage({
                count: 1, // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
                success: function (res) {
                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                    getLocalData(localIds[0]);
                }
            });
        }
		
        function getLocalData(localid) {
            $('#modal-img').show();
			//获取本地图片资源
            wx.getLocalImgData({
                localId: localid, // 图片的localID
                success: function (res) {
                    var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
                    //开始绑定
                    $.ajax({
                        url: "${pageContext.request.contextPath}/wechat/bindface",
                        type: "post",
                        data: {
                            img: localData
                        },
                        contentType: 'application/x-www-form-urlencoded;charset=utf-8',
                        async: true,
                        success: function (data) {
                            if ("SUCCESS" == data.code) {
                                location.reload();
                                $("#img").src = "../../img/${openid}.jpg?time=" +Math.random();
                                $("#addBtn").html("更新照片");
                            } else {
                                alert("" + data.message);
                            }
                        },
                        complete: function () {
                            $('#modal-img').hide();
                        }
                    })
                }
            });

        }

        $(document).ready(function () {
            $('#modal-img').hide();
            $.ajax({
                url: "${pageContext.request.contextPath}/wechat/jsapisign",
                type: "post",
                data: {
                    url: location.href.split('#')[0]
                },
                contentType: 'application/x-www-form-urlencoded;charset=utf-8',
                async: true,
                success: function (data) {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        appId: data.appid, // 必填,公众号的唯一标识
                        timestamp: data.timestamp, // 必填,生成签名的时间戳
                        nonceStr: data.nonceStr, // 必填,生成签名的随机串
                        signature: data.signature,// 必填,签名,见附录1
                        jsApiList: ["chooseImage"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                    });
                }
            })

        });
    </script>
</head>
<body>
<div class="gray-bg">
    <div class="modal-bg">
        <div class="text-center" style="width: 100%;margin-top: 100px;margin-bottom: 30px;">
            <c:if test="${hasFace}"><img id="img" src="../../img/${openid}.jpg?time=" +Math.random()  width="180" height="240"></c:if>
            <c:if test="${!hasFace}"><img src="../../resources/images/wechat/face_sign.png" width="205"
                                          height="185"></c:if>
        </div>
        <c:if test="${hasFace}">
            <h5 class="text-center span-num-text">你已成功绑定人脸</h5>
        </c:if>
        <div class="text-center" style="width: 100%;">
            <button id="addBtn" class="layui-btn btn-clickable layui-btn-lg" type="button" onclick="bindFace()">
                <c:if test="${hasFace}">更新照片</c:if>
                <c:if test="${!hasFace}">开始绑定</c:if>
            </button>
        </div>
        <h5 class="text-center span-face-info"><span class="span-face-info-title">照片要求:</span>照片需为单人照片,<br>且五官清晰、表情自然、无明显畸变
        </h5>
    </div>
    <!-- loading -->
    <div id="modal-img" class="modal-img">
        <img src="../../resources/images/wechat/loadding.gif" width="60" height="60" style="margin-top:200px"/>
    </div>
</div>
</body>
</html>

controller中请求地址为wechat/bindface的方法代码,以下代码为获取到图像信息后存储到本地磁盘,如果只是要了解微信公众号通过拍照或从手机相册中选图功能,则下面代码可不必查看。(以下代码中不相关的代码略过了,比如存储或者修改照片的标识到数据库中,在jsp中对于hasFace的判断就是查询数据库得来的,然后在转发jsp页面的代码中放到request域对象中,这些在这里也不展示)

   @RequestMapping(value = "/bindface", method = {RequestMethod.POST}, produces = MEDIATYPE_CHARSET_JSON_UTF8)
    @ResponseBody
    public String bindFace(HttpSession httpSession, String img) throws IOException {

        //没有图片信息传过来
        if (TextUtils.isEmpty(img)) {
		//在我的代码中是通过对象封装的数据,在这里直接以json形式展示,意思明白就行
            return "{'code':'CLIENT_NO_PICTURE','message':'请选择图片'}";
        }
		//传过来的img为base64编码字符串,解析
        String[] imgs = img.split("base64,");

        //解析的数据有问题
        if (imgs == null || imgs.length < 1) {
            return "{'code':'CLIENT_NO_PICTURE','message':'请选择图片'}";
        }

        //绑定人脸图片信息保存在本地磁盘,照片名称以openid命名(要在tomcat的server.xml中配置映射)
		//在Windows中设为WechatConstant.IMG_URL = "E:/images/",在linux中WechatConstant.IMG_URL = "/usr/local/images/",并在磁盘上建立对应目录下的文件夹
        Base64Util.generateImage(imgs[imgs.length - 1],WechatConstant.IMG_URL+openid+".jpg");
        return "{'code':'SUCCESS','message':'成功'}";
    }

Base64Util.java中的generateImage方法解析为图片,放入path

    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null) return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i=0;i<b.length;i++){
                if (b[i]<0){
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }catch (Exception e){
            return false;
        }
    }

要想照片再回显到微信页面,则需要在tomcat中的server.xml(D:\tomcat\apache-tomcat-8.5.29\conf)配置虚拟映射路径。

我用Nodepad++编辑server.xml,找到<Host></Host>,在它下面新建一个<Host>,配置如下:

<Host name="cmy.ngrok.xiaomiqiu.cn"  appBase="webapps"
      unpackWARs="true" autoDeploy="true">
	<!--打包的项目路径映射-->
	<Context path="" docBase="../webapps/beanWechat-rest" debug="0" reloadable="true"/>
	<!--图片存储地址,以及访问路径的映射,因为是在微信公众号中访问,所以要配置在微信公众号的外网域名下,否则无法访问-->
<!--Windows下的路径配置-->
	<Context path="/img" docBase="E:/images" debug="0" reloadable="true"/>	
<!--linux下的路径配置-->
	<Context path="/img" docBase="usr/local/images" debug="0" reloadable="true"/>			
</Host>  

把项目打包到tomcat下,启动tomcat就可以了。

猜你喜欢

转载自blog.csdn.net/qq_23543983/article/details/80438317