JAVA后台将图片与base64互转

JAVA后台将图片与base64互转

代码:

   /**
   *将图片转成base64
   */
    public static String convertFileToBase64(String imgPath) {
        String base64Str = "";
        byte[] result = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = new FileInputStream(imgPath);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            result = out.toByteArray();
            in.close();
            out.close();
            base64Str = Base64.getEncoder().encodeToString(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64Str;
    }
   /**
   *将base64转成图片
   */
    public static File getImgFileFromBase64(String base64Pic,String filePath, String fileName) throws Exception {
        File file = null;
        if (base64Pic == null) {
            System.out.println("数据为空!");
        } else {
            BASE64Decoder decoder = new BASE64Decoder();
            //处理Ajax传base64值的时候会把base64中的+换成空格
            String baseValue = base64Pic.replaceAll(" ", "+");
            //去除base64中无用的部分
            byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
            base64Pic = base64Pic.replace("base64,", "");
            SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
            String nowDate = df2.format(new Date());
            String imgFilePath = filePath + "\\" + nowDate + "\\" + System.currentTimeMillis();
            File file1 = new File(imgFilePath);
            //判断文件路径下的文件夹是否存在,不存在则创建一个新的文件
            if (!file1.exists() && !file1.isDirectory()) {
                file1.mkdirs();
            }
            try {
                for (int i = 0; i < b.length; ++i) {
                    // 调整异常数据
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                file = new File(imgFilePath + "\\" + fileName);
                // 如果要返回file文件这边return就可以了,存到临时文件中
                OutputStream out = new FileOutputStream(file.getPath());
                out.write(b);
                out.flush();
                out.close();
            } catch (Exception e) {
                System.out.println("图片存储异常!");
            }

        }
        return file;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值