一、前言
百度AI接口每天提供五百次免费图片文字提取,在这里足够满足一些简单业务和需求。
二、代码与效果
1、效果展示
2、代码实现
2.1目录结构
2.2具体实现
2.2.1身份证实体类
//定义实体类
public class IDCard {
private String address;
private String birthday;
private String name;
private String num;
private String sex;
private String nation;
public IDCard() {
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
}
2.2.2定义接口
import com.ai.model.IDCard;
public interface IDCardDao {
public IDCard getMessage(String path);
}
2.2.3接口实现
import java.net.URLEncoder;
import com.ai.dao.IDCardDao;
import com.ai.model.IDCard;
import com.ai.util.Base64Util;
import com.ai.util.FileUtil;
import com.ai.util.GetToken;
import com.ai.util.HttpUtil;
import net.sf.json.JSONObject;
public class IDCardDaoImpl implements IDCardDao {
@Override
public IDCard getMessage(String filePath) {
String idcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
IDCard card = new IDCard();
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 = GetToken.getAuth();//#####调用鉴权接口获取的token#####
String result = HttpUtil.post(idcardIdentificate, accessToken, params);
JSONObject json = JSONObject.fromObject(result);
JSONObject json1 = JSONObject.fromObject(json.get("words_result"));
JSONObject json2 = JSONObject.fromObject(json1.get("住址"));
JSONObject json3 = JSONObject.fromObject(json1.get("出生"));
JSONObject json4 = JSONObject.fromObject(json1.get("姓名"));
JSONObject json5 = JSONObject.fromObject(json1.get("公民身份号码"));
JSONObject json6 = JSONObject.fromObject(json1.get("性别"));
JSONObject json7 = JSONObject.fromObject(json1.get("民族"));
card.setAddress((String)json2.get("words"));
card.setBirthday((String)json3.get("words"));
card.setName((String)json4.get("words"));
card.setNum((String)json5.get("words"));
card.setSex((String)json6.get("words"));
card.setNation((String)json7.get("words"));
return card;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
2.2.4、后端服务
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ai.dao.impl.IDCardDaoImpl;
import com.ai.model.IDCard;
public class IdServlet extends HttpServlet {
private String piPath;
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<FileItem> items = getRequestFileItems(request);
String address =null;
String path=null;
for (FileItem item : items) {
if (!item.isFormField()) {
address = saveFile(item,request);
path=address;
}
}
IDCardDaoImpl id = new IDCardDaoImpl();
IDCard card = id.getMessage(path);
request.setAttribute("MESSAGE",card);
request.setAttribute("IMG", "picture/"+piPath);
System.out.println(path);
request.getRequestDispatcher("showmessage.jsp").forward(request,
response);
}
private List<FileItem> getRequestFileItems(HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = null;
servletContext = this.getServletConfig().getServletContext();
String str = "javax.servlet.context.tempdir";
File repository = (File) servletContext.getAttribute(str);
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
return upload.parseRequest(request);
} catch (Exception e) {
// TODO: handle exception
return null;
}
} else {
return null;
}
}
/*
* 文件处理函数2
*/
private String saveFile(FileItem item,HttpServletRequest request) {
String fileFullName = item.getName();
File fileInfo = new File(fileFullName);
String fileName = fileInfo.getName();
String str = request.getSession().getServletContext().getRealPath("/");
File savePathPicture = new File(
str+"picture");
if (!savePathPicture.exists()) {
savePathPicture.mkdirs();
}
File uploadFile = new File(savePathPicture + File.separator
+ fileName);
try {
item.write(uploadFile);
} catch (Exception e) {
// TODO: handle exception
System.out.println("保存文件失败");
}
piPath=fileName;
return savePathPicture + File.separator
+ fileName;
}
}
2.2.5相关依赖类
https://pan.baidu.com/s/1LQkZN3heppVCj6LtQ6Nb4Q
2.2.6相关依赖架包
https://pan.baidu.com/s/19nkcCrE0mtc7zqBmDb9Wmg