微信ocr身份证识别
现在人工智能崛起,很多都需要AI智能识别某些东西.
最近就接触了需要调用微信ocr智能识别身份证信息的需求.
就在这里记录一下,微信ocr接口就是 普通的表格文件上传,调用腾讯的接口
下面是代码展示:
首先需要在代码中 模拟文件上传
/**
* 身份证识别实现类
*/
@Service
public class WxOcrIdcardServiceImpl implements OcrIdcardService {
@Resource
private WxProperties wxProperties;
@Resource
private RestTemplate restTemplate;
@Resource
private IWxTokenService wxTokenServiceImpl;
//临时文件后缀
private static final String IMG_SUFFIX = ".jpg";
private String tempFileName = "";
/**
* 获取token
* @return
*/
@Override
public WxResultData verifyIdcard(byte[] file) {
//获取token(腾讯官方文档有详细获取验证码文档)
//生成微信ocr验证 url
//获取项目路径,把文件存入项目根路径
String relativelyPath=System.getProperty("user.dir");
//根据项目路径创建文件夹
String separator = File.separator;
String dir = relativelyPath+separator+"faceImage";
//生成文件名称
String generate = GuidUtil.generate();
//获取文件路径 临时存储路径
String path = getFile(file, dir, generate);
//设置file路径
Map<String, String> fileMap = new HashMap<String, String>();
fileMap.put("upfile", path);
try{
//文件上传,发送到微信端
String response = formUpload(ocrUrl, null, fileMap, "");
}
// 省略一些操作...
}
/**
* 上传图片
* @param urlStr
* @param textMap
* @param fileMap
* @param contentType 没有传入文件类型默认采用application/octet-stream
* contentType非空采用filename匹配默认的图片类型
* @return 返回response数据
*/
@SuppressWarnings("rawtypes")
public String formUpload(String urlStr, Map<String, String> textMap,
Map<String, String> fileMap,String contentType) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
//没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
contentType = new MimetypesFileTypeMap().getContentType(file);
//contentType非空采用filename匹配默认的图片类型
if(!"".equals(contentType)){
if (filename.endsWith(".png")) {
contentType = "image/png";
}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
}else if (filename.endsWith(".gif")) {
contentType = "image/gif";
}else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(
new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* 根据byte数组,生成文件
* @param bfile byte字节流
* @param filePath 文件存放目录
* @param fileName 文件名称(不带后缀的)
* @return
*/
public String getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
String path = "";
try {
File dir = new File(filePath);
if(!dir.exists()&&!dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file = File.createTempFile(fileName, IMG_SUFFIX, dir);
tempFileName = file.getName();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
path = file.getPath();
return path;
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}