直接上代码,可以直接运行。唯一需要注意的是sun.misc.BASE64Decoder 这个包可能无法引入。可以参考这个博客设置
https://blog.csdn.net/erlian1992/article/details/79518416
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sun.misc.BASE64Decoder;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class Test3 {
// 图片路劲层级分隔符
private static String separator = "/";
public static void main(String[] args) throws Base64DecodingException {
Test3 t = new Test3();
//在这里可以直接写入base64的值进行测试
String path = t.saveImg("");
//输出路径
System.out.println(path);
}
public String saveImg(String baseImg) throws Base64DecodingException {
//定义一个正则表达式的筛选规则,为了获取图片的类型
String rgex = "data:image/(.*?);base64";
String type = getSubUtilSimple(baseImg, rgex);
//去除base64图片的前缀
baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
byte[] b;
byte[] bs;
OutputStream os = null;
String fileName = "";
String nowDate = "";
// 格式化并获取当前日期(用来命名)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
nowDate = format.format(new Date());
//把图片转换成二进制
b = Base64.decode(baseImg.replaceAll(" ", "+"));
//生成路径
String path = "D:/home/upload/" + separator + "img" + separator + nowDate + separator;
//随机生成图片的名字,同时根据类型结尾
fileName = UUID.randomUUID().toString() + "." + type;
File file = new File(path);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
File imageFile = new File(path + "/" + fileName);
BASE64Decoder d = new BASE64Decoder();
// 保存
try {
bs = d.decodeBuffer(Base64.encode(b));
os = new FileOutputStream(imageFile);
os.write(bs);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.getLocalizedMessage();
}
}
}
return "img" + separator + nowDate + separator + fileName;
}
public static String getSubUtilSimple(String soap,String rgex){
Pattern pattern = Pattern.compile(rgex);
Matcher m = pattern.matcher(soap);
while(m.find()){
return m.group(1);
}
return "";
}
}