因为自己的业务需要,将图片转为base64存储到MongoDB里面去,然后vue的富文本展示
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public static String byteConverterBASE64(File file) {
long size = file.length();
byte[] imageByte = new byte[(int) size];
FileInputStream fs = null;
BufferedInputStream bis = null;
try {
fs = new FileInputStream(file);
bis = new BufferedInputStream(fs);
bis.read(imageByte);
} catch (FileNotFoundException e) {
log.error("文件" + file.getName() + "不能被找到:" + e.getMessage());
} catch (IOException e) {
log.error("byte转换BASE64出错:" + e.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
log.error("关闭输入流出错:" + e.getMessage());
}
}
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
log.error("关闭输入流出错:" + e.getMessage());
}
}
}
return (new sun.misc.BASE64Encoder()).encode(imageByte);
}
最后得到的反正差不多这种格式吧:
只是部分哦
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAO5AbgDASIAAhEBAxEB/8QAHAAAAgIDAQEAAAAAAAAAAAAAAAECAwQFBgcI/
下面也是一个base64编码解码的过程:仅供参考
public static void main(String[] args) throws Exception {
String content = "这是需要 Base64 编码的内容";
// 创建一个 Base64 编码器
BASE64Encoder base64Encoder = new BASE64Encoder();
// 执行 Base64 编码操作
String encodedString = base64Encoder.encode(content.getBytes("UTF-8"));
System.out.println( encodedString );
// 创建 Base64 解码器
BASE64Decoder base64Decoder = new BASE64Decoder();
// 解码操作
byte[] bytes = base64Decoder.decodeBuffer(encodedString);
String str = new String(bytes, "UTF-8");
System.out.println(str);
}