最近公司有业务需求,需要对企业微信中的小程序添加人脸识别功能,一般的人脸核身是对app中添加sdk完成的,考虑到业务需要,采用腾讯云的移动浮层H5接入,废话不多说,直接上代码。
这边,这3步已经满足了我们的需要。
1、配置文件
nonce是自定义的随机字符串,redirectUrl是验证成功后回调的页面
# 腾讯人脸识别配置
tencentFaceVerify:
appId: ******
appSecret: ***********************
version: 1.0.0
nonce: ************
redirectUrl: https://*****/index
2、工具类
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;
public class Base64Util {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
public Base64Util() {
}
public static String encode(String source) {
if (!isEmpty(source)) {
byte[] bytes = source.getBytes(DEFAULT_CHARSET);
String asB64 = Base64.getEncoder().encodeToString(bytes);
return asB64;
} else {
return source;
}
}
public static String decode(String source) {
if (!isEmpty(source)) {
byte[] bytes = Base64.getDecoder().decode(source);
String target = new String(bytes, DEFAULT_CHARSET);
return target;
} else {
return source;
}
}
private static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
/**
* 对字节数组字符串进行Base64解码并生成图片
* @param base64
* @param path
* @return
*/
public static boolean base64ToImage(String base64, String path) {
if (base64 == null) {
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(path);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 将一张网络图片转化成Base64字符串
* @param imgURL
* @return
*/
public static String GetImageStrFromUrl(String imgURL) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(imgURL);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);