java網路圖片Base64編碼解碼
阿新 • • 發佈:2018-12-17
編碼
/** * 線上圖片Base64編碼 * @param link 線上圖片請求地址 * @return * @throws IOException */ public static String toBase64(String link) { byte[] data = null; InputStream inputStream = null; try { URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); inputStream = conn.getInputStream(); //這裡為分界上面程式碼是拿到網路圖片,下面程式碼是編碼 data = new byte[inputStream.available()]; if (inputStream != null){ inputStream.read(data); } if (inputStream != null){ inputStream.close(); } }catch (Exception e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); }
解碼
/** * 檔案Base64解碼Java示例程式碼 * * @param str 需要解碼的字元 * @param filePath 生成檔案的路徑 * @return */ public static boolean decodeStrToFile(String str, String filePath) { if (str == null) return false; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] bytes = decoder.decodeBuffer(str); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) { bytes[i] += 256; } } OutputStream out = new FileOutputStream(filePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }