java网络图片转Base64

  • A+
所属分类:Java
 /**
     * 服务器图片转换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 编码转换为图片, 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;
    }

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: