阿里雲讀取圖片文字


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;}}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM