在手机端上测试效果如下:
点击身份证图片上传图标,将身份证的号码存到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:
身份证信息识别
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();
}
}