zhengwj-joker
应用场景:图片上传至服务器至指定目录,前端请求返回base64字符串直接显示浏览图片。
以下是工具方法,直接调用
/**
* 图片转化成base64字符串,返回的string可以直接在src上显示
* @param file 图片文件
* @param fileType 图片格式
* @return
* @throws IOException
*/
public static String getImageStr(File file, String fileType) throws IOException {
String fileContentBase64 = null;
String base64Str = "data:" + fileType + ";base64,";
String content = null;
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
//对字节数组Base64编码
if (data == null || data.length == 0) {
return null;
}
content = Base64.encodeBytes(data);
if (content == null || "".equals(content)) {
return null;
}
fileContentBase64 = base64Str + content;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
return fileContentBase64;
}

分类:

技术点:

相关文章:

  • 2020-12-25
  • 2021-08-20
  • 2021-11-04
  • 2021-04-14
  • 2021-09-21
  • 2021-11-21
  • 2021-07-16
  • 2021-11-04
猜你喜欢
  • 2021-11-20
  • 2021-12-01
  • 2020-06-26
  • 2021-04-26
  • 2021-03-30
  • 2021-12-19
  • 2021-09-16
相关资源
相似解决方案