码迷,mamicode.com
首页 > 其他好文 > 详细

从BufferedImage到InputStream,实现绘图后进行下载(生成二维码图片并下载)

时间:2014-08-23 15:19:40      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   div   log   

@SuppressWarnings("resource")
public void download() throws Exception{
    String filename = "qrcode.png";
    String content = "content";
    BufferedImage image = QRcodeUtils.encode(content, size);
    
    //BufferedImage 转 InputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
    ImageIO.write(image, "png", imageOutput);
    InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    long length = imageOutput.length();
    
    //设置response
    HttpServletResponse response = this.getResponse();
    response.setContentType("application/x-msdownload");
    response.setContentLength((int)length);
    response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("gbk"),"iso-8859-1"));
    
    //输出流
    byte[] bytes = new byte[1024];
    OutputStream outputStream = response.getOutputStream();
    long count = 0;
    while(count < length){
        int len = inputStream.read(bytes, 0, 1024);
        count +=len;
        outputStream.write(bytes, 0, len);
    }
    outputStream.flush();
}

 

从BufferedImage到InputStream,实现绘图后进行下载(生成二维码图片并下载)

标签:style   blog   http   color   os   io   ar   div   log   

原文地址:http://www.cnblogs.com/rubekid/p/3931044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!