BufferedImage에서 InputStream으로 드로잉 후 다운로드(QR코드 이미지 생성 및 다운로드)

2995 단어 BufferedImage
@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();
}

좋은 웹페이지 즐겨찾기