【JAVA】图片与BASE64互相转换

在项目中用到了图片转base64,以前没碰到过,所以在这里做个记录。
BASE64转图片

主要就是把图片转换成字节,当然你也可以通过new String(bytes,“UTF-8”); 获取字符串

 public static boolean base64ToImg(String imgbase64, String imgPath){
        if (imgbase64 == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        try(OutputStream out = new FileOutputStream(imgPath)){
            bytes = decoder.decodeBuffer(imgbase64);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0){
                    bytes[i] += 256;
                }
            }
            out.write(bytes);
            out.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
图片转BASE64
 public static boolean  imgToBase64(File file,String filePath) {
        if (file.isDirectory()) {
            System.out.println("这是文件夹" + file.getAbsolutePath());
            return false;
        } else if (file.isFile()) {
            String fileName = file.getName();
            System.out.println("-----开始处理文件----" + fileName);
            FileWriter fileWriter = null;
            byte[] bytes = null;
            BASE64Encoder encoder = new BASE64Encoder();
            try (InputStream inputStream = new FileInputStream(file)) {
                // available 获取本地文件大小
                bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                String imgdata = encoder.encode(bytes);
                File file3 = new File(filePath);
                //  创建新文件
                if (!file3.exists()) {
                    file3.createNewFile();
                }
                fileWriter = new FileWriter(file3.getAbsoluteFile(), true);
                fileWriter.write(imgdata);
                fileWriter.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }else {
            System.out.println("未知的文件");
            return false;
        }
    }

这个还是很简单的,我这里是输入的文件中去,所以需要注意流的关闭!主要就是利用了BASE64EncoderBASE64Decoder,没有太深的技术含量
DEMO资源地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值