- Give everyone a wave of codes directly
This is the Base64Util officially given by Baidu, because the official document gives the picture format parameter in the API call example as face_token (number is given in the picture library for each picture), I have been looking for a long time how to get the face_token code of the photo After choosing to give up. . . . () Because it is really difficult to handle, so I have no choice but to convert the picture to Base64 code. You can understand the Base64 code as a txt document. When you look at it, it is in text form, but it can also be converted to binary form. Similarly, each different picture, through a specific algorithm, has its fixed Base64 code, which is equivalent to a transcoding of a .jpg/.png format file, and it is a specific transcoding (may be caused by different algorithms Base64 codes are not the same), but most of them are still the same
Base64Util.java
package com.baidu.ai.aip.utils; /** * Base64 tools */ public class Base64Util { private static final char last2byte = (char) Integer.parseInt("00000011", 2); private static final char last4byte = (char) Integer.parseInt("00001111", 2); private static final char last6byte = (char) Integer.parseInt("00111111", 2); private static final char lead6byte = (char) Integer.parseInt("11111100", 2); private static final char lead4byte = (char) Integer.parseInt("11110000", 2); private static final char lead2byte = (char) Integer.parseInt("11000000", 2); private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; public Base64Util() { } public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); } }
But I don’t know how to use it at all (maybe the author is too cumbersome), because I don’t know how to pass parameters at all. Perhaps the original meaning of Baidu is through your learning of this, knowing how to do it, and then by yourself Rewrite method. However, for people like the author who is oriented to Baidu programming, this is simply impossible:) So I will post another class for everyone:
Base64ImageUtils.java
package com.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * Created by zhangwenchao on 2017/9/29. * Local or network image resources are converted to Base64 strings */ public class Base64ImageUtils { /** * @Title: GetImageStrFromUrl * @Description: Convert a network picture into a Base64 string * @param imgURL network resource location * @return Base64 string */ public static String GetImageStrFromUrl(String imgURL) { byte[] data = null; try { // Create URL URL url = new URL(imgURL); // Create link HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream(); data = new byte[inStream.available()]; inStream.read(data); inStream.close(); } catch (IOException e) { e.printStackTrace (); } // Base64 encode the byte array BASE64Encoder encoder = new BASE64Encoder(); // Return Base64 encoded byte array string return encoder.encode(data); } /** * @Title: GetImageStrFromPath * @Description: (Convert a local picture into a Base64 string) * @param imgPath * @return */ public static String GetImageStrFromPath(String imgPath) { InputStream in = null; byte[] data = null; // read picture byte array try { in = new FileInputStream(imgPath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace (); } // Base64 encode the byte array BASE64Encoder encoder = new BASE64Encoder(); // Return Base64 encoded byte array string return encoder.encode(data); } /** * @Title: GenerateImage * @Description: base64 string is converted to image * @param imgStr * @param imgFilePath image file name, such as "E:/tmp.jpg" * @return */ public static boolean saveImage(String imgStr,String imgFilePath) { if (imgStr == null) // image data is empty return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64 decoding byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] <0) {// adjust abnormal data b[i] += 256; } } // Generate jpeg pictures OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }
Complete functions, extremely easy to use, strong push, from the Internet, infringement deletion
Next are Baidu's tools
FileUtil.java
package com.baidu.ai.aip.utils; import java.io. *; /** * File reading tools */ public class FileUtil { /** * Read the content of the file and return it as a string */ public static String readFileAsString(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } if (file.length() > 1024 * 1024 * 1024) { throw new IOException("File is too large"); } StringBuilder sb = new StringBuilder((int) (file.length())); // Create byte input stream FileInputStream fis = new FileInputStream(filePath); // Create a Buffer with a length of 10240 byte[] bbuf = new byte[10240]; // Used to save the number of bytes actually read int hasRead = 0; while ( (hasRead = fis.read(bbuf)) > 0 ) { sb.append(new String(bbuf, 0, hasRead)); } fis.close(); return sb.toString(); } /** * Read byte[] array according to file path */ public static byte[] readFileByBytes(String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException(filePath); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); short bufSize = 1024; byte[] buffer = new byte[bufSize]; int len1; while (-1 != (len1 = in.read(buffer, 0, bufSize))) { bos.write(buffer, 0, len1); } byte[] var7 = bos.toByteArray(); return var7; } finally { try { if (in != null) { in.close(); } } catch (IOException var14) { var14.printStackTrace (); } bos.close(); } } } }
GsonUtils.java
/* * Copyright (C) 2017 Baidu, Inc. All Rights Reserved. */ package com.baidu.ai.aip.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import java.lang.reflect.Type; /** * Json tools. */ public class GsonUtils { private static Gson gson = new GsonBuilder().create(); public static String toJson(Object value) { return gson.toJson(value); } public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException { return gson.fromJson(json, classOfT); } public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException { return (T) gson.fromJson(json, typeOfT); } }
HttpUtil.java
package com.baidu.ai.aip.utils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map; /** * http tools */ public class HttpUtil { public static String post(String requestUrl, String accessToken, String params) throws Exception { String contentType = "application/x-www-form-urlencoded"; return HttpUtil.post(requestUrl, accessToken, contentType, params); } public static String post(String requestUrl, String accessToken, String contentType, String params) throws Exception { String encoding = "UTF-8"; if (requestUrl.contains("nlp")) { encoding = "GBK"; } return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding); } public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding) throws Exception { String url = requestUrl + "?access_token=" + accessToken; return HttpUtil.postGeneralUrl(url, contentType, params, encoding); } public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding) throws Exception { URL url = new URL(generalUrl); // Open the connection with the URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // Set general request attributes connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); // Get the requested output stream object DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(params.getBytes(encoding)); out.flush(); out.close(); // Establish the actual connection connection.connect(); // Get all response header fields Map<String, List<String>> headers = connection.getHeaderFields(); // Traverse all response header fields for (String key : headers.keySet()) { System.err.println(key + "--->" + headers.get(key)); } // Define the BufferedReader input stream to read the response of the URL BufferedReader in = null; in = new BufferedReader( new InputStreamReader(connection.getInputStream(), encoding)); String result = ""; String getLine; while ((getLine = in.readLine()) != null) { result += getLine; } in.close(); System.err.println("result:" + result); return result; } }
Ah, finally finished, sleep to sleep! ! !