前几天有个功能,其中要求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(" ", "+");这一行。加上这行之后就好使了