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

@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();
}
原文地址:https://www.cnblogs.com/rubekid/p/3931044.html