调用支付宝人脸采集查询图片Base64解码

人脸识别结果查询接口zoloz.identification.user.web.query

支付宝返回的imgStr图片字符串并不是标准的base64格式,

解析不出图片。 
由于标准的Base64并不适合直接放在URL里传输,

因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,

因此采用了一种用于URL的改进Base64编码,

如果需要转成标准base64图片格式需要通过以下方法进行转换。 

1.首先先把支付宝返回的base64转成正确的格式的base64

public static String safeUrlBase64Decode(final String imgStr ) {
    String base64Str = safeBase64Str.replace('-', '+');
base64Str = base64Str.replace('_', '/');
int mod4 = base64Str.length() % 4;
if (mod4 > 0) {
base64Str = base64Str + "====".substring(mod4);
}
return base64Str;
}

2. 然后对正确格式的base64图片进行解码
public static File base64ToFile(String base64) {
if(base64==null||"".equals(base64)) {
return null;
}
byte[] buff= Base64.decode(base64);
File file=null;
FileOutputStream fout=null;
try {
file = File.createTempFile("tmp", null);
fout=new FileOutputStream(file);
fout.write(buff);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fout!=null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
3.以上就得到了file 文件,如果需要把file文件转成流
InputStream fileInputStream = new FileInputStream(file);
 
posted @ 2019-08-06 10:07  历尽千帆归来任是少年  阅读(1029)  评论(0编辑  收藏  举报