-----有时候我们在传递图片的时候可能会需要将图片转为base64编码后再进行传送,如何将前端传递的图片进行base64编码,又如何将经过base64编码后的图片转为图片文件进行保存呢?
将图片文件进行base64编码
以下为两种方式,一直是直接将文件格式的转为base64,另一种则是以路径作为参数:
public void changeBase(MultipartFile file1,String path){
FileInputStream stream =null;
StringBuffer encode1 =new StringBuffer();
StringBuffer encode2 =new StringBuffer();
File file2 = new File(path);
try {
/*方法1:前端直接传文件*/
encode1 .append( Base64.getEncoder().encodeToString(file1.getBytes()));
//获取文件格式
String type = file1.getContentType();
//用于说明文件格式(可要可不要)
encode1.append("data:").append(type).append(";base64,");
/*方法2:前端传文件路径*/
//将文件转为流
stream = new FileInputStream(file2);
//新建一个用来存储文件二进制的数据
byte[] bytes = new byte[(int) file2.length()];
stream.read(bytes);
encode2 .append( Base64.getEncoder().encodeToString(bytes));
} catch (IOException e) {
e.printStackTrace();
}
}
将base64编码后的参数转为图片
public void changePic(String s) {
//定义一个正则表达式的筛选规则,为了获取图片的类型
String rgex = "data:image/(.*?);base64";
//获取编码后文件格式
String type = getSubUtilSimple(s, rgex);
if (StringUtils.isEmpty(type)){
type="jpeg";
}
//去除base64图片的前缀
s = s.replaceFirst("data:(.+?);base64,", "");
byte[] b;
byte[] bs;
OutputStream os = null;
String fileName = "";
//把图片转换成二进制
b = cn.hutool.core.codec.Base64.decode(s.replaceAll(" ", "+"));
//生成路径
String path = "d:/";
//随机生成图片的名字,同时根据类型结尾
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(cn.hutool.core.codec.Base64.encode(b));
os = new FileOutputStream(imageFile);
os.write(bs);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.getLocalizedMessage();
}
}
}
}
public String getSubUtilSimple(String soap,String rgex){
//生成正则函数
Pattern pattern = Pattern.compile(rgex);
Matcher m = pattern.matcher(soap);
while(m.find()){
return m.group(1);
}
return "";
}