Java 圖片URL轉Base64編碼
阿新 • • 發佈:2021-08-02
前言
實現方式:通過圖片URL獲取二進位制流,再對位元組陣列進行Base64編碼轉換
具體實現
- 實現類
import sun.misc.BASE64Encoder; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Base64Util { /** * 圖片URL轉Base64編碼 * @param imgUrl 圖片URL * @return Base64編碼 */ public static String imageUrlToBase64(String imgUrl) { URL url = null; InputStream is = null; ByteArrayOutputStream outStream = null; HttpURLConnection httpUrl = null; try { url = new URL(imgUrl); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); httpUrl.getInputStream(); is = httpUrl.getInputStream(); outStream = new ByteArrayOutputStream(); //建立一個Buffer字串 byte[] buffer = new byte[1024]; //每次讀取的字串長度,如果為-1,代表全部讀取完畢 int len = 0; //使用輸入流從buffer裡把資料讀取出來 while( (len = is.read(buffer)) != -1 ){ //用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度 outStream.write(buffer, 0, len); } // 對位元組陣列Base64編碼 return encode(outStream.toByteArray()); } catch (Exception e) { e.printStackTrace(); } finally { try { if(is != null) { is.close(); } if(outStream != null) { outStream.close(); } if(httpUrl != null) { httpUrl.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } return null; } /** * 圖片轉字串 * @param image 圖片Buffer * @return Base64編碼 */ public static String encode(byte[] image){ BASE64Encoder decoder = new BASE64Encoder(); return replaceEnter(decoder.encode(image)); } /** * 字元替換 * @param str 字串 * @return 替換後的字串 */ public static String replaceEnter(String str){ String reg ="[\n-\r]"; Pattern p = Pattern.compile(reg); Matcher m = p.matcher(str); return m.replaceAll(""); } public static void main(String[] args) { System.out.println(Base64Util.imageUrlToBase64("https://img-blog.csdnimg.cn/20210105221008901.png")); } }
- 驗證(注意新增base64頭),base64圖片線上轉換線上網址