编程语言
首页 > 编程语言> > Java 保存图片至本地 Base64

Java 保存图片至本地 Base64

作者:互联网

图片路径下载版本:

      public String saveImg(String img_url, String savename) {
        InputStream input = null;
        OutputStream os = null;

        try {
            URL url = new URL(img_url);
            // 打开URL连接
            URLConnection con = url.openConnection();
            // 得到URL的输入流
            input = con.getInputStream();
            // 设置数据缓冲
            byte[] bs = new byte[1024 * 2];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存图片至本地
            os = new FileOutputStream(aLiYunConfig.path + savename);
            while ((len = input.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (Exception e) {
            logger.error("图片保存失败:{}", e.getMessage());
        } finally {
            try {
                os.close();
                input.close();
            } catch (Exception e) {

                logger.error("数据流关闭失败:{}", e.getMessage());
            }
        }
        return "img/" + savename;
    }

Base64图片保存(base64删掉头部data:?base64,不然保存图片会有问题)

public String saveImg(String imgstr, String savename) {
        BufferedImage image = null;
        byte[] imageByte = null;
        try {
            imageByte = DatatypeConverter.parseBase64Binary(imgstr);
            image = ImageIO.read(new ByteArrayInputStream(imageByte));
            File outpuFile = new File(aLiYunConfig.path + savename);
            ImageIO.write(image,"jpg",outpuFile);
        } catch (Exception e) {
            logger.error("图片保存失败:{}", e.getMessage());
            return null;
        }
        return "img/" + savename;
    }

 

标签:savename,Java,String,img,URL,Base64,本地,new,null
来源: https://blog.csdn.net/qq_34635236/article/details/111563166