java利用阿里云身份证识别功能截取身份证头像

/ 0条评论 / 0 个点赞 / 979人阅读
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import sun.misc.BASE64Encoder;

public class ocr_idcard {
    public static String img_base64(String path) {
        /**
         *  对path进行判断,如果是本地文件就二进制读取并base64编码,如果是url,则返回
         */
        String imgBase64="";
        if (path.startsWith("http")){
            imgBase64 = path;
        }else {
            try {
                File file = new File(path);
                byte[] content = new byte[(int) file.length()];
                FileInputStream finputstream = new FileInputStream(file);
                finputstream.read(content);
                finputstream.close();
                imgBase64 = new String(Base64.encodeBase64(content));
            } catch (IOException e) {
                e.printStackTrace();
                return imgBase64;
            }
        }
        
        return imgBase64;
    }
    

	/**
	 * 图片切割
	 * 
	 * @param srcImageFile
	 *            图片地址
	 * @param responseOutputStream
	 *            servlet输出流
	 * @param w
	 *            切割宽度
	 * @param h
	 *            切割高度
	 * @param x1
	 *            开始x结点(left)
	 * @param y1
	 *            开始y结点(top)
	 * @param sw
	 *            图片宽度
	 * @param sh
	 *            图片高度
	 */
	public static void cut(String srcImageFile, int w, int h, int x1, int y1) {
		try {


			Image img;

			ImageFilter cropFilter;
			// 读取源图像
			BufferedImage bi = ImageIO.read(new File(srcImageFile));
			int sw = bi.getWidth();
			int sh = bi.getHeight();


				Image image = bi.getScaledInstance(sw, sh, Image.SCALE_DEFAULT);

				// 剪切起始坐标点
				int x = x1;
				int y = y1;

				int destWidth = w; // 切片宽度
				int destHeight = h; // 切片高度

				// 图片比例
				double pw = sw;
				double ph = sh;

				double m = (double) sw / pw;
				double n = (double) sh / ph;

				int wth = (int) (destWidth * m);
				int hth = (int) (destHeight * n);
				int xx = (int) (x * m);
				int yy = (int) (y * n);

				// 四个参数分别为图像起点坐标和宽高
				// 即: CropImageFilter(int x,int y,int width,int height)

				cropFilter = new CropImageFilter(x1-(w/2), y1-(h/2), w, h);
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));

				BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
				Graphics g = tag.getGraphics();
				g.drawImage(img, 0, 0, null); // 绘制缩小后的图
				g.dispose();
				
				File f123 = new File("d://原图.jpg");
				f123.createNewFile();
				OutputStream os = new FileOutputStream(f123);
				// 输出为文件
				ImageIO.write(tag, "JPEG", os);
				//压缩到1MB
				//压缩到目标大小
				ImgCompress.commpressPicForScale("d://原图.jpg",
						"d://ys-2.jpg",
						1024*2,0.9);
				//压缩到目标大小
				ImgCompress.commpressPicForScale("d://原图.jpg",
						"d://ys-3.jpg",
						1024*3,0.9);
				//压缩到目标大小
				ImgCompress.commpressPicForScale("d://原图.jpg",
						"d://ys-4.jpg",
						1024*4,0.9);
				//压缩到目标大小
				ImgCompress.commpressPicForScale("d://原图.jpg",
						"d://ys-5.jpg",
						1024*5,0.9);
				//压缩到目标大小
				ImgCompress.commpressPicForScale("d://原图.jpg",
						"d://ys-6.jpg",
						1024*6,0.9);
				

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	 /**
     * 将图片转换成二进制
     * @return
     */
static String getImageBinary(File f){
	BASE64Encoder encoder = new sun.misc.BASE64Encoder();  
	    BufferedImage bi;
	    try {
	        bi = ImageIO.read(f);
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();    
	        ImageIO.write(bi, "jpg", baos);    
	        byte[] bytes = baos.toByteArray();    
	        return encoder.encodeBuffer(bytes).trim();    
	    } catch (IOException e) {
	        e.printStackTrace();    
	    }    
	    return null;    
	}

    public static void main(String[] args) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "";
        String imgFile = "F:\\工作积累\\微信图片_20211213211827.jpg";
        String method = "POST";
        
        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>();
        // 对图像进行base64编码
        String imgBase64 = img_base64(imgFile);   
       
        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", "face");

        String config_str = configObj.toString();
        
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if(configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        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);
            
//            OperateImage operateImage = new OperateImage(
//            		res_obj.getJSONObject("face_rect").getJSONObject("center").getIntValue("x"),
//            		res_obj.getJSONObject("face_rect").getJSONObject("center").getIntValue("y"),
//            		res_obj.getJSONObject("face_rect").getJSONObject("size").getIntValue("width"), 
//            		res_obj.getJSONObject("face_rect").getJSONObject("size").getIntValue("height")); 
//            operateImage.srcpath = imgFile; 
//            operateImage.subpath = "d://123.JPEG"; 
//            try { 
//              operateImage.cut(); 
//            } catch (IOException e) { 
//              e.printStackTrace(); 
//            } 
            
            cut(imgFile,res_obj.getJSONObject("face_rect").getJSONObject("size").getIntValue("width"), 
            		res_obj.getJSONObject("face_rect").getJSONObject("size").getIntValue("height"), 
            		res_obj.getJSONObject("face_rect").getJSONObject("center").getIntValue("x"), 
            		res_obj.getJSONObject("face_rect").getJSONObject("center").getIntValue("y"));
            System.out.println(res_obj.toJSONString());
            String string =getImageBinary(new File("d://ys-2.jpg"));
            System.out.println(string);
            string =getImageBinary(new File("d://ys-3.jpg"));
            System.out.println(string);
            string =getImageBinary(new File("d://ys-4.jpg"));
            System.out.println(string);
            string =getImageBinary(new File("d://ys-5.jpg"));
            System.out.println(string);
            string =getImageBinary(new File("d://ys-6.jpg"));
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}