package com.offcn.TestUnti;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

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

import sun.misc.BASE64Decoder;
/**
 * 图片识别类
 * 第一个参数：几位的中英数
 * 第二个参数：图片地址
 * 返回解析好的字符串
 * @author puhui
 */
public class aliOCR {
	public static void main(String[] args) {
//		getYZM(6,"d:\\a1.jpg");
		getYZM(4,"d:\\t1.jpg");
	}
	public static String getYZM(int count,String imagePath){
		String host = "http://ali-checkcode.showapi.com";
		String path = "/checkcode";
		String method = "POST";
		Map<String, String> headers = new HashMap<String, String>();
		//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE 4afc3a5a191a4bbd80b837c3374ac872");
		Map<String, String> querys = new HashMap<String, String>();
		Map<String, String> bodys = new HashMap<String, String>();
		bodys.put("convert_to_jpg", "0");
		bodys.put("img_base64", encodeImgageToBase64(new File(imagePath)));
		bodys.put("typeId", "30"+count+"0");
		String result=null;
		try {
			HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
			result=EntityUtils.toString(response.getEntity());
			JSONObject obj = JSONObject.fromObject(result); 
			result=obj.getString("showapi_res_body");
			JSONObject obj1 = JSONObject.fromObject(result); 
			result=obj1.get("Result").toString();
			System.out.println("获取的验证码是："+obj1.get("Result"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	//图片转化成base64字符串
	public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理  
        // 其进行Base64编码处理  
        byte[] data = null;  
        // 读取图片字节数组  
        try {  
            InputStream in = new FileInputStream(imageFile);  
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return new String(Base64.encodeBase64(data));
      
    }  
	
	 //base64字符串转化成图片  
    public static boolean GenerateImage(String FilePath,String imgStr)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String imgFilePath = FilePath;//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  

    }  
    
    public static boolean getPNG(String FilePath,InputStream fis){
//		InputStream fis =null;
		FileOutputStream fos= null;
		try {
//			fis =re.asInputStream();
//			fis =re.asInputStream();
//			fos= new FileOutputStream("out/nwn2wm.png");
			fos= new FileOutputStream(FilePath);
			byte[] buf = new byte[1024];
			int len = 0;
			while((len=fis.read(buf))!=-1){
				fos.write(buf,0,len);
			}
		} catch (Exception e) {
			return false;
		}finally{
			try{
				if(fis!=null)
					fis.close();
			}catch (IOException e){
				throw new RuntimeException("读取关闭失败");
			}try{
				if(fos!=null)
					fos.close();
			}catch (IOException e){
				throw new RuntimeException("写入关闭失败");
			}
		}
		return true;
    }
}
