阿里云OCR身份证信息识别

阿里云OCR身份证信息识别

这里使用的是base64

public JSONObject getCard(MultipartFile file) {
        String host = "https://ccic.market.alicloudapi.com";
        String path = "/discern/idcard";
        String method = "POST";
        String appcode = "自己的appCode";

        //生成文件的唯一id
        String fileId =  UUID.randomUUID().toString().replace("-","");

        //获取文件后缀
        String fileSuffix = file.getName().substring(file.getName().lastIndexOf(".")+1);

		//生成文件的最终名称
        String finalName = fileId + "." + fileSuffix;

        try {
            //保存文件到指定目录
            String fileSavePath = "D:/upload/";
            File newFile = new File(fileSavePath + finalName);
            file.transferTo(newFile);
            //url = "http://127.0.0.1/static/" + finalName;
            //System.out.println(url);
            String filePath = fileSavePath + finalName;
            String base64 = ImageToBase64(filePath);
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            headers.put("Content-Type", "application/json; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            String bodys = "{\"Base64Data\":"+'"'+ base64 +'"'+ ",\"Category\":\"front\"}";
            //String bodys ="{\"ImageUrl\":"+'"'+ url +'"'+",\"Category\":\"front\"}";

            //System.out.println(bodys);

            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);
                JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                //Object json = JSONObject.toJSON(code);
                System.out.println(jsonObject);
                return jsonObject;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath     
     * @return
     */

    private static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        //System.out.println("本地图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
        return encoder.encode(Objects.requireNonNull(data));
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用Java编写阿里云OCR上传身份证的示例代码: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import com.aliyun.tea.TeaException; import com.aliyun.tea.TeaPair; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.ocr.model.v20191230.RecognizeIdentityCardRequest; import com.aliyuncs.ocr.model.v20191230.RecognizeIdentityCardResponse; import com.aliyuncs.utils.Base64Helper; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class AliyunOCRUploader { // 阿里云Access Key ID private static final String ACCESS_KEY_ID = "your_access_key_id"; // 阿里云Access Key Secret private static final String ACCESS_KEY_SECRET = "your_access_key_secret"; // 阿里云OSS Endpoint private static final String OSS_ENDPOINT = "your_oss_endpoint"; // 阿里云OSS Bucket名称 private static final String OSS_BUCKET_NAME = "your_oss_bucket_name"; public static void main(String[] args) { // 读取本地身份证图片文件并转换为Base64编码 String imagePath = "path/to/your/image"; String imageBase64 = imageToBase64(imagePath); // 初始化阿里云OCR客户端 DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", ACCESS_KEY_ID, ACCESS_KEY_SECRET); DefaultAcsClient client = new DefaultAcsClient(profile); // 构建OCR请求对象 RecognizeIdentityCardRequest request = new RecognizeIdentityCardRequest(); request.setImageBase64(imageBase64); request.setSide("face"); try { // 发送OCR请求并解析响应 RecognizeIdentityCardResponse response = client.getAcsResponse(request); String name = response.getData().getName(); String gender = response.getData().getGender(); String nationality = response.getData().getNationality(); String idNumber = response.getData().getIdNumber(); String address = response.getData().getAddress(); // 上传OCR识别结果到阿里云OSS OSS ossClient = new OSSClientBuilder().build(OSS_ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET); byte[] content = (name + "," + gender + "," + nationality + "," + idNumber + "," + address).getBytes(); InputStream inputStream = new ByteArrayInputStream(content); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(content.length); metadata.setContentType("text/plain"); String objectKey = "id_card_" + System.currentTimeMillis() + ".txt"; PutObjectRequest putObjectRequest = new PutObjectRequest(OSS_BUCKET_NAME, objectKey, inputStream, metadata); PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest); String objectUrl = "https://" + OSS_BUCKET_NAME + "." + OSS_ENDPOINT + "/" + putObjectResult.getKey(); // 打印上传结果 System.out.println("OCR识别成功,上传结果:" + objectUrl); } catch (Exception e) { throw new TeaException(e.getMessage()); } } /** * 将本地图片文件转换为Base64编码 */ private static String imageToBase64(String imagePath) { byte[] imageBytes = com.aliyun.oss.common.utils.IOUtils.readStreamAsByteArray(imagePath); List<TeaPair> headers = new ArrayList<>(); headers.add(new TeaPair("Content-Type", "application/octet-stream")); String base64 = Base64Helper.encode(imageBytes); return "data:image/jpeg;base64," + base64; } } ``` 在以上代码中,我们首先读取本地身份证图片文件,然后将其转换为Base64编码,并通过阿里云OCR SDK发送识别请求,获取OCR识别结果。最后,将OCR识别结果上传到阿里云OSS,并返回上传结果的URL。请注意,以上代码中的ACCESS_KEY_ID、ACCESS_KEY_SECRET、OSS_ENDPOINT和OSS_BUCKET_NAME需要替换为你自己的阿里云Access Key和OSS相关配置信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值