Java 将图片转成base64,传到前台展示
后台代码:
public String getBase64(SysFile sysFile){ 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字符串");
posted on 2018-04-13 17:11 程序员,贵在坚持 阅读(10567) 评论(0) 编辑 收藏 举报