• 阿里云读取图片文字


    package com.image;
    
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    import javax.imageio.ImageIO;
    import org.apache.http.HttpResponse;
    import org.apache.http.util.EntityUtils;
    import com.google.gson.Gson;
    import static org.apache.commons.codec.binary.Base64.encodeBase64;
    
    public class AliyunImages {
    
    	/**
    	 * 
    	 * @Title: test1
    	 * @Description: 识别图片文字
    	 * @param:
    	 * @author zique
    	 * @return void
    	 * @date 2018年4月20日 下午6:04:32
    	 */
    	/**
    	 * 重要提示如下: 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
    	 */
    
    	public static void main(String[] args) {
    		String host = "https://ocrapi-document.taobao.com";
    		String path = "/ocrservice/document";
    		String method = "POST";
    		String appcode = "后台可看到的appcode";//阿里云的appCode
    		Map<String, String> headers = new HashMap<String, String>();
    		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    		headers.put("Authorization", "APPCODE " + appcode);
    		// 网络图片路径
    		// String
    		// url="https://ss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=2529262901,1309013979&fm=202&mola=new&crop=v1";
    		String picture = "D:\软件安装\美图秀秀\Meitu\XiuXiu\Images\UI\btn_clip_down.png";
    		try {
    			// 获取网络图片
    			// byte[] imageFromNetByUrl = getImageFromNetByUrl(url);
    			// 获取本地图片
    			byte[] content = ReadImages(picture);
    			String encode = new String(encodeBase64(content));
    
    			// 根据API的要求,定义相对应的Content-Type
    			headers.put("Content-Type", "application/json; charset=UTF-8");
    			Map<String, String> querys = new HashMap<String, String>();
    			Map<String, String> objBodys = new HashMap<String, String>();
    
    			objBodys.put("img", encode);// 二进制图片
    			// objBodys.put("url",url );
    			Gson gson = new Gson();
    			String bodys = gson.toJson(objBodys);
    
    			// String bodys =
    			// "{//图像数据:base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,和url参数只能同时存在一个"img":"",//图像url地址:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,和img参数只能同时存在一个"url":"",//是否需要识别结果中每一行的置信度,默认不需要。true:需要false:不需要"prob":false}";
    
    			HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
    
    			int statusCode = response.getStatusLine().getStatusCode();
    			System.out.println(EntityUtils.toString(response.getEntity()));
    			System.out.println(response.toString() + "返回的状态码" + statusCode);
    			// 获取response的body
    			// System.out.println(EntityUtils.toString(response.getEntity()));
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * @author 将图片转换成二进制
    	 * @created 2018/6/11
    	 * @version V2.6
    	 */
    	public static byte[] getImageFromNetByUrl(String strUrl) throws Exception {
    		try {
    			if (null == strUrl) {
    				return null;
    			}
    			URL url = new URL(strUrl);
    			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    			conn.setRequestMethod("GET");
    			conn.setConnectTimeout(5 * 1000);
    			InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
    			byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
    			return btImg;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    
    	/**
    	 * 
    	 * @Title: readInputStream
    	 * @Description: 读取图片,将图片转换成二进制
    	 * @param: @param
    	 *             inStream
    	 * @param: @return
    	 * @param: @throws
    	 *             Exception
    	 * @author zique
    	 * @return byte[]
    	 * @date 2018年7月20日 下午6:45:47
    	 */
    	public static byte[] readInputStream(InputStream inStream) throws Exception {
    		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    		byte[] buffer = new byte[1024];
    		int len = 0;
    		while ((len = inStream.read(buffer)) != -1) {
    			outStream.write(buffer, 0, len);
    		}
    		inStream.close();
    		return outStream.toByteArray();
    	}
    
    	/**
    	 * "C:\Users\Administrator\Desktop\file.jpg"
    	 * 
    	 * @Title: ReadImages
    	 * @Description: 将本地图片转换成二进制
    	 * @param: @return
    	 * @author zique
    	 * @return byte[]
    	 * @date 2018年7月23日 上午9:27:54
    	 */
    	public static byte[] ReadImages(String images) {
    		File f = new File(images);
    		BufferedImage bi;
    		try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    			// 获取图片的后缀名
    			String name = f.getName().substring(f.getName().indexOf(".") + 1, f.getName().length());
    			bi = ImageIO.read(f);
    			ImageIO.write(bi, name, baos); // 经测试转换的图片是格式这里就什么格式,否则会失真
    			byte[] bytes = baos.toByteArray();
    			return bytes;
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    }
    

      

    HttpUtils需要使用到下面的依赖  

    package com.image;
    
    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.lang3.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);
            }
        }
    }

    package com.image;
    import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import java.util.Map;import javax.imageio.ImageIO;import org.apache.http.HttpResponse;import org.apache.http.util.EntityUtils;import com.google.gson.Gson;import static org.apache.commons.codec.binary.Base64.encodeBase64;
    public class AliyunImages {
    /** *  * @Title: test1 * @Description: 识别图片文字 * @param: * @author diyueyu * @return void * @date 2018年7月20日 下午6:04:32 *//** * 重要提示如下: 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 */
    public static void main(String[] args) {String host = "https://ocrapi-document.taobao.com";String path = "/ocrservice/document";String method = "POST";String appcode = "2c0edc09ff2449219e81df812a774f5b";//阿里云的appCodeMap<String, String> headers = new HashMap<String, String>();// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);// 网络图片路径// String// url="https://ss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=2529262901,1309013979&fm=202&mola=new&crop=v1";String picture = "D:\软件安装\美图秀秀\Meitu\XiuXiu\Images\UI\btn_clip_down.png";try {// 获取网络图片// byte[] imageFromNetByUrl = getImageFromNetByUrl(url);// 获取本地图片byte[] content = ReadImages(picture);String encode = new String(encodeBase64(content));
    // 根据API的要求,定义相对应的Content-Typeheaders.put("Content-Type", "application/json; charset=UTF-8");Map<String, String> querys = new HashMap<String, String>();Map<String, String> objBodys = new HashMap<String, String>();
    objBodys.put("img", encode);// 二进制图片// objBodys.put("url",url );Gson gson = new Gson();String bodys = gson.toJson(objBodys);
    // String bodys =// "{//图像数据:base64编码,要求base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,和url参数只能同时存在一个"img":"",//图像url地址:图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,和img参数只能同时存在一个"url":"",//是否需要识别结果中每一行的置信度,默认不需要。true:需要false:不需要"prob":false}";
    HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
    int statusCode = response.getStatusLine().getStatusCode();System.out.println(EntityUtils.toString(response.getEntity()));System.out.println(response.toString() + "返回的状态码" + statusCode);// 获取response的body// System.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}}
    /** * @author 将图片转换成二进制 * @created 2018/6/11 * @version V2.6 */public static byte[] getImageFromNetByUrl(String strUrl) throws Exception {try {if (null == strUrl) {return null;}URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5 * 1000);InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据return btImg;} catch (Exception e) {e.printStackTrace();return null;}}
    /** *  * @Title: readInputStream * @Description: 读取图片,将图片转换成二进制 * @param: @param *             inStream * @param: @return * @param: @throws *             Exception * @author 狄跃宇 * @return byte[] * @date 2018年7月20日 下午6:45:47 */public static byte[] readInputStream(InputStream inStream) throws Exception {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();}
    /** * "C:\Users\Administrator\Desktop\file.jpg" *  * @Title: ReadImages * @Description: 将本地图片转换成二进制 * @param: @return * @author 狄跃宇 * @return byte[] * @date 2018年7月23日 上午9:27:54 */public static byte[] ReadImages(String images) {File f = new File(images);BufferedImage bi;try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {// 获取图片的后缀名String name = f.getName().substring(f.getName().indexOf(".") + 1, f.getName().length());bi = ImageIO.read(f);ImageIO.write(bi, name, baos); // 经测试转换的图片是格式这里就什么格式,否则会失真byte[] bytes = baos.toByteArray();return bytes;} catch (IOException e) {e.printStackTrace();}return null;}}

    当一个人在成长过程中,慢慢的享受学习,那么这个人就在成长,在往自己目标的方向奔跑.
  • 相关阅读:
    TechED 2005 : 《实战基于SPS2003的知识管理系统》
    《SharePoint Portal Server 2003 深入指南》即将完稿 & 大纲
    ows.js里面的ctx和itemTable到底有哪些参数?
    用代码获取SharePoint站点中InfoPath表单的数据
    新年快乐!
    Office with .Net 系列之 ――― 在自己的程序中宿主Office
    如何在WebPart中访问页面上的其他WebPart
    将SPS中被FrontPage修改过的页面重置为Ghost Page
    Office with .Net 系列之 ――― 在自己的程序中宿主Office
    ASP.NET 2.0与SharePoint 2.0
  • 原文地址:https://www.cnblogs.com/zique/p/9353089.html
Copyright © 2020-2023  润新知