java實現圖片轉化成base64字符串前端頁面直接顯示


應用場景:圖片上傳至服務器至指定目錄,前端請求返回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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM