從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();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM