微信公眾號開發之調起拍照或從手機相冊中選圖接口


拍照或從手機相冊中選圖接口
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" οnclick="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就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM