JAVA后台将图片与base64互转
代码:
/**
*将图片转成base64
*/
public static String convertFileToBase64(String imgPath) {
String base64Str = "";
byte[] result = null;
// 读取图片字节数组
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = new FileInputStream(imgPath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
result = out.toByteArray();
in.close();
out.close();
base64Str = Base64.getEncoder().encodeToString(result);
} catch (IOException e) {
e.printStackTrace();
}
return base64Str;
}
/**
*将base64转成图片
*/
public static File getImgFileFromBase64(String base64Pic,String filePath, String fileName) throws Exception {
File file = null;
if (base64Pic == null) {
System.out.println("数据为空!");
} else {
BASE64Decoder decoder = new BASE64Decoder();
//处理Ajax传base64值的时候会把base64中的+换成空格
String baseValue = base64Pic.replaceAll(" ", "+");
//去除base64中无用的部分
byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
base64Pic = base64Pic.replace("base64,", "");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
String nowDate = df2.format(new Date());
String imgFilePath = filePath + "\\" + nowDate + "\\" + System.currentTimeMillis();
File file1 = new File(imgFilePath);
//判断文件路径下的文件夹是否存在,不存在则创建一个新的文件
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
try {
for (int i = 0; i < b.length; ++i) {
// 调整异常数据
if (b[i] < 0) {
b[i] += 256;
}
}
file = new File(imgFilePath + "\\" + fileName);
// 如果要返回file文件这边return就可以了,存到临时文件中
OutputStream out = new FileOutputStream(file.getPath());
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
System.out.println("图片存储异常!");
}
}
return file;
}