应用场景:图片上传至服务器至指定目录,前端请求返回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.close();
//对字节数组Base64编码
if (data == null || data.length == 0) {
return null;
}
content = deBytes(data);
if (content == null || "".equals(content)) {
return null;
}
fileContentBase64 = base64Str + content;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
return fileContentBase64;
}
本文发布于:2024-01-30 01:26:39,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170654920318258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |