java 图片转base64 ------- 云服务地址

发布于:2022-11-29 ⋅ 阅读:(193) ⋅ 点赞:(0)
/**
 * 云地址图片转换base64 path:云地址图片路径  返回 base64编码(String 类型)
 * @param path
 * @return
 */
public static String imgToBase64(String path){
    byte[] data = null;
    InputStream in = null;
    ByteArrayOutputStream out = null;
    try{
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        in = connection.getInputStream();
        out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len =in.read(b)) != -1){
            out.write(b,0,len);
        }
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try{
            if(in != null ){
                in.close();
            }
        }catch (IOException e){
            e.getStackTrace();
        }
    }
    System.out.println("转换后的图片大小:"+out.toByteArray().length/1024);
    BASE64Encoder base = new BASE64Encoder();
    return base.encode(out.toByteArray());
}