持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情
目录
download.csdn.net/download/qq…
Base64是什么
Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。 Base64编码是从二进制到字符的过程,可用于在HTTP环境下传递较长的标识信息。采用Base64编码具有不可读性,需要解码后才能阅读。 Base64由于以上优点被广泛应用于计算机的各个领域,然而由于输出内容中包括两个以上“符号类”字符(+, /, =),不同的应用场景又分别研制了Base64的各种“变种”。为统一和规范化Base64的输出,Base62x被视为无符号化的改进版本。
标准的Base64并不适合直接放在URL里传输,因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作通配符。 为解决此问题,可采用一种用于URL的改进Base64编码,它在末尾填充'='号,并将标准Base64中“+”和“/”分别改成了“-”和“”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象标识符的格式。 另有一种用于正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”,因为“+”,“”以及前面在IRCu中用到的“[”和“]”在正则表达式中都可能具有特殊含义。 此外还有一些变种,它们将“+/”*改为“-”或“.”(用作编程语言中的标识符名称)或“.-”(用于XML中的Nmtoken)甚至“:”(用于XML中的Name)。 Base64要求把每三个8Bit的字节转换为四个6Bit的字节(38 = 46 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
Base64转换成图片
编辑
android studio build乱码
在Android Studio中双击Shift或者点击顶部全局搜索"Edit Custom VM Options"
或者点击Help—>Edit Custom VM Options
然后在打开的文件中添加一句
-Dfile.encoding=UTF-8
编辑
效果:
编辑
找不到okio.ByteString
编辑 缺少jar包
编辑
接腾讯人脸识别
导入jar包
编辑
导入项目包
编辑
调用代码
第一种:
//人脸比对
public static String Appkey="LTAIRUYY7bruQUA";
public static String AppScreat="ohXnElaRTUmEL1qj4RbOAjMumI6Zl";
public static Float picCompareTencent(String ImageA,String ImageB,String UrlA,String UrlB) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try{
// 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
Credential cred = new Credential("AKIDSko6Y8vXydNvJYmrmR4uLZcUO8KM1X", "Xza0FJO9jHk061kHH8pOn49HK62rpd");
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("iai.tencentcloudapi.com");
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
IaiClient client = new IaiClient(cred, "ap-beijing", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
CompareFaceRequest req = new CompareFaceRequest();
req.setImageA(ImageA);
req.setImageB(ImageB);
req.setUrlA(UrlA);
req.setUrlB(UrlB);
// 返回的resp是一个CompareFaceResponse的实例,与请求对象对应
CompareFaceResponse resp = client.CompareFace(req);
// 输出json格式的字符串回包
System.out.println(CompareFaceResponse.toJsonString(resp));
return resp.getScore();
} catch (TencentCloudSDKException e) {
return null ;
}
}
第2种:
// 腾讯人脸比对
private void upAli(String path1) {
showLoadingDialog("人脸比对中...");
String image1 = BitmapUtils.imageToBase64(path1);//拍照的头像base64编码格式
;//头像的base64编码格式
LogUtils.w("image1 " + image1);
LogUtils.w("image2 " + image2);
new Thread(new Runnable() {
@Override
public void run() {
Map<String, Object> map = new HashMap<>();
map.put("ImageA", image1);
map.put("ImageB", image2);
Gson gson = new Gson();
String param = gson.toJson(map);
//发送请求 本地封装的https 请求
String response = AuthFace.getAuthTC3("CompareFace", param, AuthFace.Version);//DetectFace
handler2.post(new Runnable() {
@Override
public void run() {
try {
//处理json 数据 把JSON数据转化为对象
JSONObject jsonObject = new JSONObject(response.toString());
dissLoadingDialog();
//返回错误提示
if (jsonObject.getJSONObject("Response").has("Error")) {
String Message = jsonObject.getJSONObject("Response").getJSONObject("Error").getString("Message");
String RequestId = jsonObject.getJSONObject("Response").getString("RequestId");
String Code = jsonObject.getJSONObject("Response").getJSONObject("Error").getString("Code");
compareDialog.showResultAnimation(1, Message);
} else {
//正确的人脸检测反馈
double FaceAttributesInfo = jsonObject.getJSONObject("Response").getDouble("Score");
Log.e("人脸对比", FaceAttributesInfo + "");
if (FaceAttributesInfo > 60) {
compareDialog.showResultAnimation(0, "比对成功");
} else {
compareDialog.showResultAnimation(1, "经图片比对为同一个人的可信度不高!");
}
}
} catch (JSONException e) {
Log.e("JSON error", e.getMessage());
dissLoadingDialog();
ToastUtils.show(mcontext, "人脸比对异常");
}
}
});
}
}).start();
// myTask = new MyTask();
// myTask.execute(Utils.FaceUrl, image1, image2);
}
package com.zhongxin.learninglibrary.activitys.user;
import android.util.Log;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class AuthFace {
private static String SecretId = "KIDSk0Mo6Y8vXydNvJYmrmR4uLZcUO8KM1X";
private static String SecretKey = "za0FJO9jHk061kHH8pOn49HKk062rpd";
private static String Url = "https://iai.tencentcloudapi.com";
//规范请求串
private static String HTTPRequestMethod = "POST";
private static String CanonicalURI = "/";
private static String CanonicalQueryString = "";
private static String CanonicalHeaders = "content-type:application/json; charset=utf-8\nhost:iai.tencentcloudapi.com\n";
private static String SignedHeaders = "content-type;host";//参与签名的头部信息
//签名字符串
private static String Algorithm = "TC3-HMAC-SHA256";
private static String Service = "iai";
private static String Stop = "tc3_request";
//版本
public static String Version = "2020-03-03";
//接入地域
public static String Region = "ap-beijing";
/**
* v3鉴权
* @param action 方法名
* @param paramJson json化的参数
* @param version 版本号 2018-03-01
* @return
*/
public static String getAuthTC3(String action, String paramJson, String version){
Log.i("人脸对比0", paramJson);
try{
String hashedRequestPayload = HashEncryption(paramJson);
String CanonicalRequest =
HTTPRequestMethod + '\n' +
CanonicalURI + '\n' +
CanonicalQueryString + '\n' +
CanonicalHeaders + '\n' +
SignedHeaders + '\n' +
hashedRequestPayload;
//时间戳
Date date = new Date();
//微秒->秒
String timestamp = String.valueOf(date.getTime() / 1000);
//格林威治时间转化
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+0"));
String dateString = formatter.format(date.getTime());
//签名字符串
String credentialScope = dateString + "/" + Service + "/" + Stop;
String hashedCanonicalRequest = HashEncryption(CanonicalRequest);
String stringToSign = Algorithm + "\n" +
timestamp + "\n" +
credentialScope + "\n" +
hashedCanonicalRequest;
//计算签名
byte[] secretDate = HashHmacSha256Encryption(("TC3" + SecretKey).getBytes("UTF-8"), dateString);
byte[] secretService = HashHmacSha256Encryption(secretDate, Service);
byte[] secretSigning = HashHmacSha256Encryption(secretService, Stop);
//签名字符串
byte[] signatureHmacSHA256 = HashHmacSha256Encryption(secretSigning, stringToSign);
StringBuilder builder = new StringBuilder();
for (byte b : signatureHmacSHA256) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
builder.append(hex);
}
String signature = builder.toString().toLowerCase();
//组装签名字符串
String authorization = Algorithm + ' ' +
"Credential=" + SecretId + '/' + credentialScope + ", " +
"SignedHeaders=" + SignedHeaders + ", " +
"Signature=" + signature;
//创建header 头部
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", authorization);
headers.put("Host", "iai.tencentcloudapi.com");
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("X-TC-Action", action);
headers.put("X-TC-Version", version);
headers.put("X-TC-Timestamp", timestamp);
headers.put("X-TC-Region", Region);
//request 请求
String response = resquestPostData(Url, paramJson, headers);
Log.i("人脸对比1", response);
return response;
}catch(Exception e){
return e.getMessage();
}
}
/*
* Function : 发送Post请求到服务器
* Param : params请求体内容,encode编码格式
*/
public static String resquestPostData(String strUrlPath, String data, Map<String, String> headers) {
try {
URL url = new URL(strUrlPath);
//代理
// Proxy proxyset = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 12639));
// HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(proxyset);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置header
if (headers.isEmpty()) {
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
} else {
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpURLConnection.setRequestProperty(key, value);
}
}
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length()));
//获得输出流,向服务器写入数据
if (data != null) {
byte[] writebytes = data.getBytes();
// 设置文件长度
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
}
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream); //处理服务器的响应结果
}
} catch (IOException e) {
return "err: " + e.getMessage().toString();
}
return "-1";
}
/*
* Function : 封装请求体信息
* Param : params请求体内容,encode编码格式
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //存储封装好的请求体信息
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1); //删除最后的一个"&"
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
/*
* Function : 处理服务器的响应结果(将输入流转化成字符串)
* Param : inputStream服务器的响应输入流
*/
public static String dealResponseResult(InputStream inputStream) {
String resultData = null; //存储处理结果
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
}
/**
*
*/
private static String HashEncryption(String s) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(s.getBytes());
//替换java DatatypeConverter.printHexBinary(d).toLowerCase()
StringBuilder builder = new StringBuilder();
for (byte b : sha.digest()) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
builder.append(hex);
}
return builder.toString().toLowerCase();
}
private static byte[] HashHmacSha256Encryption(byte[] key, String msg) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
mac.init(secretKeySpec);
return mac.doFinal(msg.getBytes("UTF-8"));
}
}
怎么判断ImageView 为空
@BindView(R.id.userHeaderImage)
ImageView userHeaderImage;
if (userHeaderImage.getDrawable()==null){
ToastUtils.show(VertifyInfoActivity.this,"头像信息不存在");
}else {
goCamera();
}