印刷文字识别-行驶证识别使用记录

一,前言

因业务需要,系统需要实现行驶证识别功能。本着节约时间成本,循序渐进的原则,该功能直接调用阿里的相关接口,现将调试过程记录在下。

二,正文

1,接口地址:

https://market.aliyun.com/products/57002003/cmapi011791.html?spm=5176.2020520132.101.5.2dbb7218f8T1AG#sku=yuncode579100000

2,在线调试:

3,接下来就是把这项功能移动到项目当中去

(1)antd+react前端上传照片:

组件初始化

class VehicleLicenseTab extends Component {
    state = {
        previewVisible: false,
        previewImage: '',
        positiveList:[],
        contraryList:[],
        workId: null,
        positivePhoto:null,//正面照片
        contraryPhoto:null,//反面照片
        positiveWordsState:false,//正面照片置空标识
        contraryWordsState:false,//反面照片置空标识

    };

操作函数:

handleCancel = () => this.setState({ previewVisible: false });//关闭窗口

    handlePreview = (file) => {//预览图片
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    };
    handleChange = ({ fileList }) => this.setState({ fileList });//事件触发

    handlePositiveChange = (e) =>{//事件触发具体函数
        this.setState({positiveList:e.fileList});
        if(e.file.response!==undefined){
            //console.log("----handlePositiveChange--"+JSON.stringify(e.file.response.fileName))
            this.setState({positivePhoto:e.file.response.positivePhoto});
        }
        if(this.state.positiveWordsState){//删除时,将该图片对象置空
            this.setState({positivePhoto:null});
        }
        this.setState({positiveWordsState:false})

    };
    handleContraryChange = (e) =>{
        this.setState({contraryList:e.fileList});
        if(e.file.response!==undefined){
            //console.log("----handleContraryChange--"+JSON.stringify(e.file.response.fileName))
            this.setState({contraryPhoto:e.file.response.positivePhoto});
        }
        if(this.state.contraryWordsState){//删除时,将该图片对象置空
            this.setState({contraryPhoto:null});
        }
        this.setState({contraryWordsState:false})
    }

    handlePositiveRemove =(file) =>{//删除事件
        delAtta(this.props.workId,'vehiclelicense/positive',file.response.fileName);
        this.setState({positiveWordsState:true});
    }
    handleContraryRemove =(file) =>{
        delAtta(this.props.workId,'vehiclelicense/contrary',file.response.fileName);
        this.setState({contraryWordsState:true});
    }


    beforeUpload =(file) =>{//上传限制,大小或格式
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        if (!isJPG) {
            message.error('只能上传JPG文件!');
        }
        const isLt50M = file.size / 1024 / 1024 < 1.5;
        if (!isLt50M) {
            message.error('文件大小必须小于1.5MB!');
        }
        return isJPG && isLt50M;
    };

渲染:

render() {
        const { previewVisible, previewImage, positiveList,contraryList,positivePhoto,contraryPhoto} = this.state;
        const {form} = this.props;
        // this.getCarPhoto();deng
        const actionURL=config.HOST+'/cardIdentification/post/';
        const positiveData={userToken: JSON.parse(localStorage.getItem('user')).token,
            workId:this.props.workId,
            type:'positive',
            catalog:'vehiclelicense/positive'};
        const contraryData={userToken: JSON.parse(localStorage.getItem('user')).token,
            workId:this.props.workId,
            type:'contrary',
            catalog:'vehiclelicense/contrary'};

        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">请上传行驶证</div>
            </div>
        );

        const {getFieldDecorator} = form;
        const formItemLayout = {
            labelCol: {span: 8},
            wrapperCol: {span: 8},
        };

 布局代码:略。

(2)提交请求:

通过antd的upload的封装的url将请求发送给后端控制层进行处理。

(3)请求处理:后端

package com.xy.loan.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
/**
 * 图像识别类控制层
 * @author Administrator
 *
 */
import com.alibaba.fastjson.JSONObject;
import com.xy.loan.bc.CustomerModelNameBc;
import com.xy.loan.bc.DBStatus;
import com.xy.loan.entity.ContractFile;
import com.xy.loan.exception.LoanBizExceptionCode;
import com.xy.loan.util.HttpUtils;
import com.xy.loan.util.ModelHelper;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import static org.apache.commons.codec.binary.Base64.encodeBase64;
@Controller
@RequestMapping("cardIdentification")
public class CardIdentificationController extends BaseController{
	
	@Value("#{settings['upload.path']}")
	private String uploadPath;
	@Value("#{settings['upload.path.photo']}")
	private String uploadPathPhoto;
	/**
	 * 上传图片
	 * @param model
	 * @param request
	 * @param file
	 */
	@RequestMapping(value = "/post", method = RequestMethod.POST)
	public void post(Model model, HttpServletRequest request, @RequestParam("file") MultipartFile file) {
		String catalog = request.getParameter("catalog");
		String workId = request.getParameter("workId");
		String type = request.getParameter("type");
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				//TODO 乱码解决的临时方法
				String filePath = getFileDir(workId, catalog,type);
//				String fileName = file.getOriginalFilename();
				String fileName = (System.currentTimeMillis())+".jpg";//时间戳重命名图片,
//				String fileRealName = CustomerModelNameBc.valueToCode(fileName);
				File fileTo = new File(filePath+fileName);
				// 转存文件
				file.transferTo(fileTo);
				String host = "https://dm-53.data.aliyun.com";
		        String path = "/rest/160601/ocr/ocr_vehicle.json";
		        String appcode = "1f7d4b7f96214b61876ee4abf9c55b46";
//		        String imgFile = "/opt/www/files/files/1/carphoto/body/timg.jpg";
		        Boolean is_old_format = false;//如果文档的输入中含有inputs字段,设置为True, 否则设置为False
		        //请根据线上文档修改configure字段
		        JSONObject configObj = new JSONObject();
		        if("positive".equals(type)){
		        	configObj.put("side", "face");
		        	}else{
			        configObj.put("side", "back");
		        	}
		        String config_str = configObj.toString();
		        //            configObj.put("min_size", 5);
		        //            String config_str = "";

		        String method = "POST";
		        Map<String, String> headers = new HashMap<String, String>();
		        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		        headers.put("Authorization", "APPCODE " + appcode);

		        Map<String, String> querys = new HashMap<String, String>();

		        // 对图像进行base64编码
		        String imgBase64 = "";
		        try {
//		            File file1 = new File(imgFile);
		            byte[] content = new byte[(int) fileTo.length()];
		            FileInputStream finputstream = new FileInputStream(fileTo);
		            finputstream.read(content);
		            finputstream.close();
		            imgBase64 = new String(encodeBase64(content));
		        } catch (IOException e) {
		            e.printStackTrace();
		            return;
		        }
		        // 拼装请求body的json字符串
		        JSONObject requestObj = new JSONObject();
		        try {
		            if(is_old_format) {
		                JSONObject obj = new JSONObject();
		                obj.put("image", getParam(50, imgBase64));
		                if(config_str.length() > 0) {
		                    obj.put("configure", getParam(50, config_str));
		                }
		                JSONArray inputArray = new JSONArray();
		                inputArray.add(obj);
		                requestObj.put("inputs", inputArray);
		            }else{
		                requestObj.put("image", imgBase64);
		                if(config_str.length() > 0) {
		                    requestObj.put("configure", config_str);
		                }
		            }
		        } catch (JSONException e) {
		            e.printStackTrace();
		        }
		        String bodys = requestObj.toString();

		        try {
		            /**
		             * 重要提示如下:
		             * HttpUtils请从
		             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
		             * 下载
		             *
		             * 相应的依赖请参照
		             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
		             */
		            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
		            int stat = response.getStatusLine().getStatusCode();
		            if(stat != 200){
		                System.out.println("Http code: " + stat);
		                System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
		                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
		                return;
		            }

		            String res = EntityUtils.toString(response.getEntity());
		            JSONObject res_obj = JSON.parseObject(res);
		            if(is_old_format) {
		                JSONArray outputArray = res_obj.getJSONArray("outputs");
		                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
		                JSONObject out = JSON.parseObject(output);
		                System.out.println(out.toJSONString());
		            }else{
		                System.out.println("-行驶证:-"+res_obj.toJSONString());
		            }
		            model.addAttribute("positivePhoto", res_obj);
		            model.addAttribute("fileName", fileName);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
				ModelHelper.addValidateInfo(model, LoanBizExceptionCode.EXCEPTION_10000000);
			} catch (Exception e) {
				e.printStackTrace();
				ModelHelper.addValidateInfo(model, LoanBizExceptionCode.EXCEPTION_10000002);
			}
		}
	}
	
	/**
	 * 获取上传路径
	 * @param workId
	 * @param catalog
	 * @return
	 */
	private String getFileDir(String workId, String catalog,String type) {
		String dirPath = "";
		// 车辆照片保存到图片目录
		if (StringUtils.isNotBlank(catalog) && catalog.contains("carphoto")) {
			dirPath = uploadPathPhoto;
		} else if (StringUtils.isNotBlank(catalog)) {
			dirPath = uploadPath;
		}
		//合同模板上传
		if ("contractModel".equals(type)) {
			dirPath = dirPath+ catalog;
		}else {
			// uploadPath ;//+ File.separatorChar + workId;
			if (workId != null && !("".equals(workId))&&!("undefined".equals(workId))) {
				dirPath = dirPath + File.separatorChar + workId+File.separatorChar;
			}
			if (catalog != null && !("null".equals(catalog))) {
				dirPath = dirPath + File.separatorChar + catalog+File.separatorChar;
			}
		}
		File dir = new File(dirPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dirPath;
	}

	
	
	
	public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }
	
	/**
	 * 删除附件
	 * 
	 * @param model
	 * @param workId
	 * @param catalog
	 * @param fileName
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public void delete(Model model, String workId, String catalog, String fileName,String type,String filePath) {
		try {
			if (StringUtils.isEmpty(filePath)) {//有文件路径的时候直接按照路径删除
				filePath = getFileDir(workId, catalog,type) + fileName;
			}
			File file = new File(filePath);
			if (file.delete()) {
				ModelHelper.addValidateInfo(model, LoanBizExceptionCode.EXCEPTION_10000000);
				return;
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}

		ModelHelper.addValidateInfo(model, LoanBizExceptionCode.EXCEPTION_10000002);
	}
}

 HttpUtils.java(请求处理工具类)

package com.xy.loan.util;
/**
 * 用于行驶证图像识别
 * @author Administrator
 *
 */
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {
	/**
	 * get
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doGet(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			Map<String, String> bodys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }	
	
	/**
	 * Post String
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Post stream
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put String
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put stream
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Delete
	 *  
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doDelete(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    	StringBuilder sbUrl = new StringBuilder();
    	sbUrl.append(host);
    	if (!StringUtils.isBlank(path)) {
    		sbUrl.append(path);
        }
    	if (null != querys) {
    		StringBuilder sbQuery = new StringBuilder();
        	for (Map.Entry<String, String> query : querys.entrySet()) {
        		if (0 < sbQuery.length()) {
        			sbQuery.append("&");
        		}
        		if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
        			sbQuery.append(query.getValue());
                }
        		if (!StringUtils.isBlank(query.getKey())) {
        			sbQuery.append(query.getKey());
        			if (!StringUtils.isBlank(query.getValue())) {
        				sbQuery.append("=");
        				sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
        			}        			
                }
        	}
        	if (0 < sbQuery.length()) {
        		sbUrl.append("?").append(sbQuery);
        	}
        }
    	
    	return sbUrl.toString();
    }
	
	private static HttpClient wrapClient(String host) {
		HttpClient httpClient = new DefaultHttpClient();
		if (host.startsWith("https://")) {
			sslClient(httpClient);
		}
		
		return httpClient;
	}
	
	private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                	
                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                	
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
        	throw new RuntimeException(ex);
        }
    }
}

 OK,大功告成:最终效果

猜你喜欢

转载自blog.csdn.net/qq_38793958/article/details/82835000
今日推荐