base64转图片,保存之后图片打不开

 前几天有个功能,其中要求base64转图片,结果保存之后图片打不开,找了半天终于发现了问题,在此记录一下。

下面是转换图片的部分代码。

//文件保存路径+全名
File localFile = new File(attachment2.getAccpath() + attachment2.getFilename());
if (!localFile.exists()) {
	File parent = localFile.getParentFile();
	if (!parent.exists()) {
		parent.mkdirs();
	}
		localFile.createNewFile();
}
		
BASE64Decoder decoder = new BASE64Decoder();
//去除头的base64
String cotent = split[1];
//关键是这一句,不加这一句就会出现文件损坏的情况
String replace = cotent.replace(" ", "+");
byte[] b = decoder.decodeBuffer(replace);
for (int i = 0; i < b.length; ++i) {
	if (b[i] < 0) {
		b[i] += 256;
	}
}
OutputStream out = new FileOutputStream(attachment2.getAccpath()+attachment2.getFilename());
out.write(b);
out.flush();
out.close();

问题就出现在String replace = cotent.replace(" ", "+");这一行。加上这行之后就好使了

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值