RT,遇到一个需求,base64图片码存数据库的,然后需要显示为图片,(浏览器可以展示base64图片码),这边非浏览器端。
总之接口那边需要的是图片,不是码。
废话不多说,直接上码:
建一个 Base64ImgRender.java
import com.jfinal.render.Render; import com.jfinal.render.RenderException; import javax.servlet.ServletOutputStream; import java.io.IOException; import java.util.Base64; /** * base64 图片码 转 图片流 */ public class Base64ImgRender extends Render { private String base64Img; public Base64ImgRender(String base64Img) { this.base64Img = base64Img; } public void render() { response.setHeader("Pragma","no-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/png"); try { Base64.Decoder decoder = Base64.getDecoder(); // 去掉base64前缀 data:image/jpeg;base64, base64Img = base64Img.substring(base64Img.indexOf(",", 1) + 1); byte[] b = decoder.decode(base64Img); // 处理数据 for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(b); outputStream.flush(); outputStream.close(); } catch (IOException e) { throw new RenderException(e); } } }
Controller 中使用:
String avatar = x.getStr("avatar"); render(new Base64ImgRender(avatar));
搞定~
祝大家端午快乐~