在手机端上测试效果如下:
点击身份证图片上传图标,将身份证的号码存到input中,其他信息则放在table中。
步骤一:调用百度api卡证识别接口
安装上图的步骤到身份证识别接口,按照上面给的步骤一一执行即可,我用的是java语言写的接口调用后台,需要下载三个java工具类(其实有四个,最后一个json的工具类,我没有用)。
后台代码:
1.controll:
@Controller
public class BaiduOcrController {
@Autowired
private BaiduOcrService baiduOcrService;
@RequestMapping({"/baidu_ocr_sfz.do"})
public void getCompanyCar( HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
response.getWriter().println(baiduOcrService.getSFZ(request));
}
}
2.service:
public interface BaiduOcrService {
public String getSFZ(HttpServletRequest request);
}
3.serviceImpl:
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import com.feiwei.dsc.ssss.service.BaiduOcrService;
import com.feiwei.dsc.ssss.util.Base64Util;
import com.feiwei.dsc.ssss.util.FileUtil;
import com.feiwei.dsc.ssss.util.HttpUtil;
import com.feiwei.dsc.ssss.util.OrderTypeFormatUtil;
@Service("baiduOcrService")
public class BaiduOcrServiceImpl implements BaiduOcrService{
@Override
public String getSFZ(HttpServletRequest request) {
// 身份证识别url
String idcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
// 本地图片路径
String filePath = OrderTypeFormatUtil.getAttribute(request, "filePath");
try {
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
String params = "id_card_side=front&" + URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(imgStr, "UTF-8");
/**
* 线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
*/
String accessToken = "24.3dec12eb735fd3803a43a2f5a584bb86.2592000.1512445812.282335-10324927";
String result = HttpUtil.post(idcardIdentificate, accessToken, params);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
步骤二:前台mui上传代码
前台将身份证图片上传成功之后,调用身份证识别接口传上传文件的地址即可。
1.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/mui.min.css" rel="stylesheet" />
<style type="text/css">
body {background:white; position:relative; }
.conter{background:white; overflow:hidden;}
.inp {height:30px!important; margin-top:9px; border:1px solid #CCCCCC!important; text-align:center; float:left !important; width:40% !important; font-size:12px; background:url(images/select.png) no-repeat center right !important;}
.cnp {height:30px!important; margin-top:9px; border:1px solid #CCCCCC!important; text-indent:10px; float:left !important; width:40% !important; font-size:12px; border-radius: 5px !important;}
.iz { width:30%; font-size:14px; padding:11px 10px!important; text-align:center;}
.fd {float:left !important; clear: none !important; width:33%!important; box-sizing:border-box;}
.mui-input-group .mui-input-row:after,.mui-input-group:after {height:0px !important;}
.hide{display:none;}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=71vwhDVH0K9gfrx2qL3NSdR9Pq3lxbEF"></script>
<script src="js/appPhotoUp.js"></script>
<script src="js/appConfig.js"></script>
<script src="js/mui.min.js"></script>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">身份证信息识别</h1>
</header>
<div class="mui-content ">
<input type="hidden" id="myaddress" />
<div class="mui-input-row" style="display:-webkit-flex; display:flex;">
<label>身份证:</label>
<input type="text" id="customerIdCard1" class="mui-input-clear cnp" placeholder="身份证号码" >
<input type="hidden" id="customerIdCarFileUrlImage1" />
![](images/camra.png)
![](images/add.png)
</div>
<table>
<li>姓名:<span style="color: green;" id="xm"></span></li>
<li>民族:<span style="color: green;" id="mz"></span></li>
<li>性别:<span style="color: green;" id="xb"></span></li>
<li>住址:<span style="color: green;" id="zz"></span></li>
<li>出生:<span style="color: green;" id="cs"></span></li>
<li>公民身份号码:<span style="color: green;" id="gm"></span></li>
</table>
</div>
</body>
</html>
2.js:
appConfig.js文件:
var ctx = "http://个人电脑ip:8080/";
var URL_SFZ = ctx + "baidu_ocr_sfz.do";
var URL_UPLOAD_PIC = ctx + "feiwei_upload_pic.do";
appPhotoUp.js文件(此文件包含了图片加水印代码):
var checkDriveCard="";
function G(id){
return document.getElementById(id);
}
//点击头像上传图片
function showPhoto(id) {
if(document.getElementById(id).value == "") {
mui.alert("尚未上传照片。");
return;
}
localStorage.setItem("fileId", document.getElementById(id).value);
mui.openWindow({
url: 'picDetail.html',
id: 'picDetail'
});
};
//点击头像上传图片
function myphoto(id) {
if(mui.os.plus) {
var a = [{
title: "拍照"
}, {
title: "从手机相册选择"
}];
plus.nativeUI.actionSheet({
cancel: "取消",
buttons: a
}, function(b) { /*actionSheet 按钮点击事件*/
switch(b.index) {
case 0:
break;
case 1:
clickCamera(id); /*拍照*/
break;
case 2:
clickGallery(id); /*打开相册*/
break;
default:
break;
}
})
}
};
// 拍照
function clickCamera(id) {
var cmr = plus.camera.getCamera();
var res = cmr.supportedImageResolutions[0];
var fmt = cmr.supportedImageFormats[0];
cmr.captureImage(function(path) {
plus.io.resolveLocalFileSystemURL(path, function(entry) {
var localUrl = entry.toLocalURL();
plus.zip.compressImage({
src: localUrl,
dst: "_doc/chat/camera/" + localUrl,
quality: 20,
overwrite: true
}, function(e) {
uploadHead(e, id);
}, function(err) {
console.log("压缩失败: " + err.message);
});
});
}, function(err) {
console.error("拍照失败:" + err.message);
}, {
index: 1
});
};
function clickGallery(id) {
plus.gallery.pick(function(path) {
console.log(path);
var str = "" + path;
if(str.substr(str.length - 4, 4) != ".jpg" && str.substr(str.length - 4, 4) != ".png") {
mui.alert("该图片格式不正确。");
return;
}
plus.zip.compressImage({
src: path,
dst: "_doc/chat/gallery/" + path,
quality: 20,
overwrite: true
}, function(e) {
uploadHead(e, id);
}, function(err) {
console.error("压缩失败:" + err.message);
});
}, function(err) {});
};
//上传头像图片
function uploadHead(e, id) {
//服务端接口路径
var server = URL_UPLOAD_PIC;
//打开等待旋转提示按钮
var wt = plus.nativeUI.showWaiting("正在上传图片,请稍候。。。");
var task = plus.uploader.createUpload(server, {
method: "post"
}, function(t, status) {
console.log(status);
if(status == 200) {
var obj = JSON.parse(t.responseText);
mui.alert("上传成功");
localStorage.setItem("fileId","D://apache-tomcat-8.0.43//webapps//fwkj//"+obj.fileId);
mui.ajax(URL_SFZ,{
data:{
filePath:localStorage.getItem("fileId")
},
dataType: 'json', //服务器返回json格式数据
type: 'post', //HTTP请求类型
timeout: 10000, //超时时间设置为10秒;
success: function(data){
document.getElementById("xm").innerHTML=data.words_result.姓名.words;
document.getElementById("mz").innerHTML=data.words_result.民族.words;
document.getElementById("xb").innerHTML=data.words_result.性别.words;
document.getElementById("zz").innerHTML=data.words_result.住址.words;
document.getElementById("cs").innerHTML=data.words_result.出生.words;
document.getElementById("gm").innerHTML=data.words_result.公民身份号码.words;
document.getElementById("customerIdCard1").value=data.words_result.公民身份号码.words;
},
error: function() {
mui.alert("无法获取数据");
}
})
if(obj.resultCode == "OK") {
G(id).value = obj.fileId;
if(checkDriveCard=="1"){
seeDriverMessge(obj.driverInfo.data);
checkDriveCard="";
}
} else {
mui.alert("上传失败");
}
wt.close(); //关闭等待提示按钮
} else {
alert("上传失败:" + status);
wt.close(); //关闭等待提示按钮
}
});
task.addFile(e.target, {
key: "testdoc"
});
//添加其他参数
task.addData("address", document.getElementById("myaddress").value);
task.addData("checkDriveCard",checkDriveCard);
task.start();
}
涉及到图片上传代码,一并都将代码放出来
1.controll:
@Controller
class FWAPPFileController{
@Autowired
private FWAPPFileService fWAPPFileService;
@RequestMapping({"/feiwei_upload_pic.do"})
public void uploadPic(HttpServletRequest request, HttpServletResponse response, ModelMap model)
throws Exception
{
response.getWriter().println(this.fWAPPFileService.uploadPic(request));
}
}
2.service:
public interface FWAPPFileService
{
public String uploadPic(HttpServletRequest paramHttpServletRequest);
}
3.serviceImpl:
@Service("FWAPPFileService")
public class FWAPPFileServiceImpl implements FWAPPFileService {
public String uploadPic(HttpServletRequest request) {
JSONObject jo = new JSONObject();
jo.put("resultCode", "NG");
String contentType = request.getContentType();
String address = OrderTypeFormatUtil.getAttribute(request, "address");
if ((contentType != null) && (contentType.toLowerCase().startsWith("multipart/"))) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("testdoc");
System.out.println(file.getOriginalFilename());
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String ctime = formatter.format(new Date());
String fileId = "imageUpload//F" + ctime + String.valueOf((int) (Math.random() * 9000.0D) + 1000) + ".jpg";
String path = request.getSession().getServletContext().getRealPath("");
System.out.println(path + fileId);
InputStream fis = null;
FileOutputStream fos = null;
try {
fis = file.getInputStream();
fos = new FileOutputStream(path + fileId);
byte[] bytes = new byte[1024];
int n = 0;
while ((n = fis.read(bytes)) != -1) {
fos.write(bytes);
}
} catch (Exception e) {
e.printStackTrace();
try {
fis.close();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
File file2=null;
try{
file2=new File(path + fileId);//要识别的文件路径
}catch(Exception e){
return "";
}
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
String ctime2 = formatter2.format(new Date());
addWaterMark(path + fileId, path + fileId, ctime2 , address);
jo.put("resultCode", "OK");
jo.put("fileId", fileId);
return jo.toString();
}
return jo.toString();
}
}