圖片url轉base64


/**
     * 通過圖片的url獲取圖片的base64字符串
     * @param imgUrl    圖片url
     * @return    返回圖片base64的字符串
     */
    public static String image2Base64(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編碼
            BASE64Encoder base64Encoder = new BASE64Encoder();
            return base64Encoder.encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

圖片url轉base64


免責聲明!

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



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