Java生成图片二维码并下载

1.导入依赖


    com.google.zxing
    core
    3.3.0

2.工具类qrcodeutils

public class QrcodeUtils {
    public static void downloadQrcode(String content, HttpServletResponse response, HttpServletRequest request) throws Exception {
        //转换字符,避免中文乱码问题
        content = new String(content.getBytes("UTF-8"),"ISO-8859-1");

        Hashtable hintMap = new Hashtable();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);  // 矫错级别
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 900, 900, hintMap);
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(900, 900, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < matrixWidth; i++){
            for (int j = 0; j < matrixWidth; j++){
                if (byteMatrix.get(i, j)){
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        /**
         * 将image转换成流
         */
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=qrcode.jpg");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();

        response.getOutputStream().write(imageInByte);

        response.getOutputStream().flush();

        response.getOutputStream().close();

    }
}

3.使用

    3.1控制器:

@GetMapping("/downLoadQrcode")
public ResultBean downLoadQrcode(Long shopId, HttpServletResponse response, HttpServletRequest request){
    try {
        qrcoceBusiness.downloadQrcode("http://wx1.great-info.tech/?shopId="+shopId,response,request);
    } catch (Exception e) {
        e.printStackTrace();
        return new ResultBean<>(ServiceCode.DELETE_FAILURE,ServiceCode.DELETE_FAILURE_MSG);
    }
    return new ResultBean<>(ServiceCode.OK,ServiceCode.OK_DEFAULT_MSG);
}

  3.2调用utils

public void downloadQrcode(String content, HttpServletResponse response, HttpServletRequest request) throws Exception {
    QrcodeUtils.downloadQrcode(content,response,request);
}

 

你可能感兴趣的:(java小知识)