package org.jeecg.modules.system.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.stream.FileImageInputStream;

import org.json.JSONObject;

import com.baidu.aip.ocr.AipOcr;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BaiduUtil {
	
    public static final String APP_ID = "23890069";
    public static final String API_KEY = "ZOLqyLPBF4I0pejNpZzvzf35";
    public static final String SECRET_KEY = "VR8pmnk997sDVBkMXusTDsrUksCAbb4Z";
    
    public static AipOcr client = null;
    
    static{
    	client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    }
    
    /**
     * 印章识别
     * @param imgUrl 本地图片地址
     * @return
     * {
	    "result":[
	        {
	            "major":{
	                "probability":0.9989657998,
	                "words":"德阳玺合印章有限公司送检样章"
	            },
	            "minor":[
	
	            ],
	            "probability":0.9393941164,
	            "location":{
	                "top":30,
	                "left":58,
	                "width":578,
	                "height":577
	            },
	            "type":"circle"
	        }
	    ],
	    "log_id":1730486846918069925,
	    "result_num":1
	   }
     */
    public static JSONObject seal(String imgUrl) {
    	byte[] image = readImageFile(imgUrl);
		// 调用印章识别
        JSONObject fileResult = client.seal(image);	
        log.info("-----------百度识别印章fileResult----------"+fileResult);
        return fileResult;
    }
    
    public static void main(String args[]) {
    	seal("D:\\Download\\860237437.jpg");
    }
    
    public static byte[] readImageFile(String path) {
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		} catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
		} catch (IOException ex1) {
			ex1.printStackTrace();
		}
		return data;
	}

}
