• 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;
        }
    
  • 相关阅读:
    Spring框架概念
    git stash 用法总结和注意点
    Java虚拟机:对象创建过程与类加载机制、双亲委派模型
    办公软件技巧
    Zookeeper到底是干嘛的
    ANdroid Studio下载
    node.js网络(net)
    显示日期
    打包apk

  • 原文地址:https://www.cnblogs.com/Honglu/p/15660412.html
Copyright © 2020-2023  润新知