Java中通过图片路径转base64格式,之后转回图片格式在下载到本地

修改一下BASE64Decoder decoder = new BASE64Decoder();打包有些可能会出现问题,修改为Base64.Decoder decoder = Base64.getDecoder();

1.图片转为base64格式代码

File file = new File("C:\\Users\\1\\Desktop\\123.png");
        byte[] data = null;
        InputStream inputStream = new FileInputStream(file);
        // 读取图片字节数组
        try{
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String faceBinaryData = java.util.Base64.getEncoder().encodeToString(data);
        System.out.println(faceBinaryData);

2.通过base64转为图片下载下来

private static String GenerateImage(String base64str, String savePath){
        try {
            //对字节数组字符串进行Base64解码并生成图片
            if (base64str == null || base64str.equals("")) {
                throw new XException("传入的图片base64为空串!");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String path = savePath + "/" +simpleDateFormat.format(new Date());;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
//            BASE64Decoder decoder = new BASE64Decoder();
			Base64.Decoder decoder = Base64.getDecoder();

            //Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), ".png", file);

            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(b);
            outputStream.flush();
            outputStream.close();
            int indexOf = tempFile.getPath().indexOf("Desktop");
            return tempFile.getPath().substring(indexOf - 1).replaceAll("\\\\","/");

        }catch (Exception e) {
            return  null;
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值