Java 圖片URL轉Base64編碼


前言

實現方式:通過圖片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"));
    }

}


- End -
夢想是咸魚
關注一下吧


免責聲明!

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



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