Java实现网络图片转Base64

远程服务器图片转换为Base64编码

 /**
     * 服务器图片转换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());
    }

Base64编码转换为图片输出

    /**
     * base64 编码转换为图片, base:base64编码 字符串  path:转换完之后的图片存储地址
     * @param base
     * @param path
     * @return
     */
    public static boolean base64ToImg(String base,String path){
        if(StringUtil.isBlank(base)){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try{
            byte[] bytes = decoder.decodeBuffer(base);
            for(int i = 0;i < bytes.length; ++i){
                if(bytes[i] < 0){
                    bytes[i]+=256;
                }
            }
            out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
            }catch (IOException e){
                e.getStackTrace();
            }
        }
        return true;
    }
posted @ 2021-12-08 10:58  过往入尘土  阅读(2600)  评论(0编辑  收藏  举报