服务端字节流输出图片
import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; @Controller @RequestMapping("/imgs/") public class test { @RequestMapping("test") public void test(HttpServletResponse response) throws IOException { //写给浏览器 response.setContentType("image/jpeg"); //浏览器不要缓存 response.setDateHeader("expries", -1); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); BufferedImage buffImg = ImageIO.read(new FileInputStream("g://timg.jpg")); ImageIO.write(buffImg, "jpg", response.getOutputStream()); } @RequestMapping("test1") public void test1(HttpServletResponse response) throws IOException { try { response.setContentType("image/jpeg"); OutputStream toClient = response.getOutputStream(); String xmlImg = GetImageStr("g://timg.jpg"); GenerateImage(xmlImg, toClient); } catch (Exception ex) { System.out.println(ex.toString()); } } @RequestMapping("test2") public void test2(HttpServletResponse response) throws IOException { try { response.setContentType("text/html"); String xmlImg = GetImageStr("g://timg.jpg"); System.out.println(xmlImg); response.getWriter().write("<html><body><img src='data:image/jpeg;base64,"+xmlImg+"'/></body></html>"); } catch (Exception ex) { System.out.println(ex.toString()); } } public static boolean GenerateImage(String imgStr, OutputStream out) { if (imgStr == null) // 图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } public static String GetImageStr(String imgFilePath) { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 byte[] data = null; // 读取图片字节数组 try { InputStream in = new FileInputStream(imgFilePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);//返回字符串 } }
转载来自:https://www.cnblogs.com/1-Admin/p/8029949.html
作者:涛先森の日常
出处:https://www.cnblogs.com/it-taosir/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。