圖片轉化為base64,傳到前台展示
public String getBase64(){ String imgStr = ""; try { File file = new File("C:\\EThinkTankFile\\20180402160120431.jpg"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fis.close(); BASE64Encoder encoder = new BASE64Encoder(); imgStr = encoder.encode(buffer); } catch (Exception e) { e.printStackTrace(); } return "data:image/jpeg;base64,"+imgStr; }前台代碼:<img id="picture" width="690" height="460" src="">通過ajax 請求將后台返回的字符串 添加到src屬性中去 $("#picture").attr("src","后台返回的base64字符串");
文件流轉化為base64,傳到前台展示
public static String getBase64FromInputStream(InputStream in) { // 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理 byte[] data = null; // 讀取圖片字節數組 try { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = in.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } data = swapStream.toByteArray(); } catch (IOException e) { LOGGER.error("InputStream轉換成base64失敗:{}", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOGGER.error("InputStream轉換成base64失敗:{}", e); } } } //返回的字符串傳到前台,添加到src屬性中去,即可顯示圖片 return "data:image/jpeg;base64,"+ new String(Base64.encodeBase64(data)); }
