java获取网络图片转为base64格式

/**
     * 将网络路径图片转为base64的格式
     * @param requestUrl 请求网络路径
     * @param photoType 响应的格式(png,jpg,ico等)
     * @throws Exception
     */
    public static String getUrlImageToBase64(String requestUrl, String photoType) throws Exception {
    
    
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
    
    
            // 创建URL
            URL url = new URL(requestUrl);
            byte[] by = new byte[1024];

            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream is = conn.getInputStream();

            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
    
    
                data.write(by, 0, len);
            }

            // 关闭流
            is.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        return "data:image/" + photoType + ";base64," + encoder.encodeToString(data.toByteArray());
    }

猜你喜欢

转载自blog.csdn.net/gelinwangzi_juge/article/details/125769628